| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
"""Formatters.""" |
| 13 |
|
| 14 |
import logging |
| 15 |
import typing |
| 16 |
|
| 17 |
from pythonjsonlogger import json as jsonlogger |
| 18 |
|
| 19 |
from daiquiri import types |
| 20 |
|
| 21 |
|
| 22 |
DEFAULT_FORMAT = ( |
| 23 |
"%(asctime)s [%(process)d] %(color)s%(levelname)-8.8s " |
| 24 |
"%(name)s: %(message)s%(color_stop)s" |
| 25 |
) |
| 26 |
|
| 27 |
DEFAULT_EXTRAS_FORMAT = ( |
| 28 |
"%(asctime)s [%(process)d] %(color)s%(levelname)-8.8s " |
| 29 |
"%(name)s%(extras)s: %(message)s%(color_stop)s" |
| 30 |
) |
| 31 |
|
| 32 |
|
| 33 |
class ColorFormatter(logging.Formatter): |
| 34 |
"""Colorizes log output.""" |
| 35 |
|
| 36 |
|
| 37 |
LEVEL_COLORS = { |
| 38 |
logging.DEBUG: "\033[00;32m", |
| 39 |
logging.INFO: "\033[00;36m", |
| 40 |
logging.WARN: "\033[01;33m", |
| 41 |
logging.ERROR: "\033[01;31m", |
| 42 |
logging.CRITICAL: "\033[01;31m", |
| 43 |
} |
| 44 |
|
| 45 |
COLOR_STOP = "\033[0m" |
| 46 |
|
| 47 |
def add_color(self, record: types.ColoredLogRecord) -> None: |
| 48 |
"""Add color to a record.""" |
| 49 |
if getattr(record, "_stream_is_a_tty", False): |
| 50 |
record.color = self.LEVEL_COLORS[record.levelno] |
| 51 |
record.color_stop = self.COLOR_STOP |
| 52 |
else: |
| 53 |
record.color = "" |
| 54 |
record.color_stop = "" |
| 55 |
|
| 56 |
def remove_color(self, record: types.ColoredLogRecord) -> None: |
| 57 |
"""Remove color from a record.""" |
| 58 |
del record.color |
| 59 |
del record.color_stop |
| 60 |
|
| 61 |
def format(self, record: logging.LogRecord) -> str: |
| 62 |
"""Format a record.""" |
| 63 |
record = typing.cast(types.ColoredLogRecord, record) |
| 64 |
self.add_color(record) |
| 65 |
s = super(ColorFormatter, self).format(record) |
| 66 |
self.remove_color(record) |
| 67 |
return s |
| 68 |
|
| 69 |
|
| 70 |
class ExtrasFormatter(logging.Formatter): |
| 71 |
"""Formats extra keywords into %(extras)s placeholder. |
| 72 |
|
| 73 |
Any keywords passed to a logging call will be formatted into a |
| 74 |
"extras" string and included in a logging message. |
| 75 |
|
| 76 |
Example: |
| 77 |
logger.info('my message', extra='keyword') |
| 78 |
|
| 79 |
will cause an "extras" string of: |
| 80 |
[extra: keyword] |
| 81 |
|
| 82 |
to be inserted into the format in place of %(extras)s. |
| 83 |
|
| 84 |
The optional `keywords` argument must be passed into the init |
| 85 |
function to enable this functionality. Without it normal daiquiri |
| 86 |
formatting will be applied. Any keywords included in the |
| 87 |
`keywords` parameter will not be included in the "extras" string. |
| 88 |
|
| 89 |
Special keywords: |
| 90 |
|
| 91 |
keywords |
| 92 |
A set of strings containing keywords to filter out of the |
| 93 |
"extras" string. |
| 94 |
|
| 95 |
extras_template |
| 96 |
A format string to use instead of '[{0}: {1}]' |
| 97 |
|
| 98 |
extras_separator |
| 99 |
What string to "join" multiple "extras" with. |
| 100 |
|
| 101 |
extras_prefix and extras_suffix |
| 102 |
Strings which will be prepended and appended to the "extras" |
| 103 |
string respectively. These will only be prepended if the |
| 104 |
"extras" string is not empty. |
| 105 |
""" |
| 106 |
|
| 107 |
def __init__( |
| 108 |
self, |
| 109 |
keywords: typing.Optional[typing.Set[str]] = None, |
| 110 |
extras_template: str = "[{0}: {1}]", |
| 111 |
extras_separator: str = " ", |
| 112 |
extras_prefix: str = " ", |
| 113 |
extras_suffix: str = "", |
| 114 |
*args: typing.Any, |
| 115 |
**kwargs: typing.Any, |
| 116 |
) -> None: |
| 117 |
self.keywords = set() if keywords is None else keywords |
| 118 |
self.extras_template = extras_template |
| 119 |
self.extras_separator = extras_separator |
| 120 |
self.extras_prefix = extras_prefix |
| 121 |
self.extras_suffix = extras_suffix |
| 122 |
super(ExtrasFormatter, self).__init__(*args, **kwargs) |
| 123 |
|
| 124 |
def add_extras(self, record: types.ExtrasLogRecord) -> None: |
| 125 |
if not hasattr(record, "_daiquiri_extra_keys"): |
| 126 |
record.extras = "" |
| 127 |
return |
| 128 |
|
| 129 |
extras = self.extras_separator.join( |
| 130 |
self.extras_template.format(k, getattr(record, k)) |
| 131 |
for k in record._daiquiri_extra_keys |
| 132 |
if k != "_daiquiri_extra_keys" and k not in self.keywords |
| 133 |
) |
| 134 |
if extras != "": |
| 135 |
extras = self.extras_prefix + extras + self.extras_suffix |
| 136 |
record.extras = extras |
| 137 |
|
| 138 |
def remove_extras(self, record: types.ExtrasLogRecord) -> None: |
| 139 |
del record.extras |
| 140 |
|
| 141 |
def format(self, record: logging.LogRecord) -> str: |
| 142 |
record = typing.cast(types.ExtrasLogRecord, record) |
| 143 |
self.add_extras(record) |
| 144 |
s = super(ExtrasFormatter, self).format(record) |
| 145 |
self.remove_extras(record) |
| 146 |
return s |
| 147 |
|
| 148 |
|
| 149 |
class ColorExtrasFormatter(ColorFormatter, ExtrasFormatter): |
| 150 |
"""Combines functionality of ColorFormatter and ExtrasFormatter.""" |
| 151 |
|
| 152 |
def format(self, record: logging.LogRecord) -> str: |
| 153 |
record = typing.cast(types.ColoredLogRecord, record) |
| 154 |
self.add_color(record) |
| 155 |
s = ExtrasFormatter.format(self, record) |
| 156 |
self.remove_color(record) |
| 157 |
return s |
| 158 |
|
| 159 |
|
| 160 |
class DatadogFormatter(jsonlogger.JsonFormatter): |
| 161 |
def __init__(self) -> None: |
| 162 |
super(DatadogFormatter, self).__init__(timestamp=True) |
| 163 |
|
| 164 |
def add_fields( |
| 165 |
self, |
| 166 |
log_record: typing.Dict[str, typing.Any], |
| 167 |
record: logging.LogRecord, |
| 168 |
message_dict: typing.Dict[str, str], |
| 169 |
) -> None: |
| 170 |
super(DatadogFormatter, self).add_fields(log_record, record, message_dict) |
| 171 |
log_record["status"] = record.levelname.lower() |
| 172 |
log_record["logger"] = { |
| 173 |
"name": record.name, |
| 174 |
} |
| 175 |
if record.exc_info and record.exc_info[0]: |
| 176 |
log_record["error"] = { |
| 177 |
"kind": record.exc_info[0].__name__, |
| 178 |
"stack": message_dict.get("stack_info"), |
| 179 |
"message": message_dict.get("exc_info"), |
| 180 |
} |
| 181 |
log_record.pop("exc_info", None) |
| 182 |
log_record.pop("stack_info", None) |
| 183 |
|
| 184 |
|
| 185 |
TEXT_FORMATTER = ColorExtrasFormatter(fmt=DEFAULT_EXTRAS_FORMAT) |
| 186 |
JSON_FORMATTER = jsonlogger.JsonFormatter() |
| 187 |
DATADOG_FORMATTER = DatadogFormatter() |