Вот как я инициализирую свой регистратор в моем main.py файл и две строки примера моего вызова для регистрации сообщения:
Код: Выделить всё
logger = logging.getLogger(__name__)
hostname = socket.gethostname()
host_ip = subprocess.run([r"ip -4 addr show ztjlhzlhyj | grep -oP '(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'"], capture_output=True, text=True, shell=True).stdout.splitlines()[0].strip()
logging.LoggerAdapter(logging.getLogger(__name__), extra={"hostname": hostname, "ip": host_ip})
# Truncated code
logger.debug("Loading env...", extra={"hostname": hostname, "ip": host_ip}) # Example where I implicitly add the extra on the debug call.
# Truncated code
logger.error(e) # Example where I don't add it manually but where the LoggerAdapter should take care of it.
Код: Выделить всё
LOG_RECORD_BUILTIN_ATTRS = {
"args",
"asctime",
"created",
"exc_info",
"exc_text",
"filename",
"funcName",
"levelname",
"levelno",
"lineno",
"module",
"msecs",
"message",
"msg",
"name",
"pathname",
"process",
"processName",
"relativeCreated",
"stack_info",
"thread",
"threadName",
"taskName",
}
class MaxJSONFormatter(logging.Formatter):
def __init__(self, *, fmt_keys: Optional[dict[str, str]] = None):
super().__init__()
with open("stupid_test.log", "a+") as f:
f.write(json.dumps(fmt_keys))
f.write("\n")
self.fmt_keys = fmt_keys if fmt_keys is not None else dict()
def format(self, record: logging.LogRecord) -> str:
message = self._prepare_log_dict(record)
return json.dumps(message, default=str)
def _prepare_log_dict(self, record: logging.LogRecord) -> dict:
always_fields = {
"message": record.getMessage(),
"timestamp": datetime.fromtimestamp(
record.created, tz=timezone.utc
).isoformat()
}
if record.exc_info is not None:
always_fields["exc_info"] = self.formatException(record.exc_info)
if record.stack_info is not None:
always_fields["stack_info"] = self.formatStack(record.stack_info)
message = {
key: msg_val
if (msg_val := always_fields.pop(val, None)) is not None
else getattr(record, val)
for key, val in self.fmt_keys.items()
}
with open("stupid_test.log", "a+") as f:
f.write(json.dumps(getattr(record, "extra"), default=None))
f.write("\n")
f.write(json.dumps(record))
f.write("\n")
# Need to figure out the extra tag not working
message.update(always_fields)
message.update(getattr(record, "extra", {}))
for key, val in record.__dict__.items():
if key not in LOG_RECORD_BUILTIN_ATTRS:
message[key] = val
with open("stupid_test.log", "a+") as f:
f.write(json.dumps(message))
f.write("\n")
return message
class MaxDBHandler(logging.Handler):
def __init__(self):
super().__init__()
load_dotenv()
connection_string = f"DRIVER={{FreeTDS}};SERVERNAME={env('DB_SERVER')};DATABASE={env('DATABASE')};UID={env('DB_USERNAME')};PWD={env('DB_PASSWORD')};"
# connectio_string ONLY FOR LOCAL TESTING ONLY
# connection_string = f"DRIVER={{SQL Server}};SERVER={env('DB_SERVER')};DATABASE={env('DATABASE')};UID={env('DB_USERNAME')};PWD={env('DB_PASSWORD')};"
self.db = pyodbc.connect(connection_string)
def emit(self, record):
with self.db.cursor() as cursor:
cursor.execute("INSERT INTO app_log (log) VALUES (?)", (self.format(record),))
class MaxQueueHandler(QueueHandler):
def __init__(self, handlers: list[str], respect_handler_level: bool):
super().__init__(queue=multiprocessing.Queue(-1))
self.handlers = handlers
self.respect_handler_level = respect_handler_level
Код: Выделить всё
{
"version": 1,
"disable_existing_loggers": false,
"formatters": {
"simple": {
"format": "[%(levelname)s]: %(message)s"
},
"detailed": {
"format": "[%(levelname)s|%(module)s|%(lineno)d] - %(asctime)s: %(message)s",
"datefmt": "%Y-%m-%dT%H:%M:%S%z"
},
"json": {
"()": "maxlogger.MaxJSONFormatter",
"fmt_keys": {
"level": "levelname",
"message": "message",
"timestamp": "timestamp",
"logger": "name",
"module": "module",
"function": "funcName",
"line": "lineno",
"thread_name": "threadName",
"extra": "extra"
}
}
},
"handlers": {
"stderr": {
"class": "logging.StreamHandler",
"level": "WARNING",
"formatter": "detailed",
"stream": "ext://sys.stderr"
},
"file": {
"class": "logging.handlers.RotatingFileHandler",
"level": "DEBUG",
"formatter": "detailed",
"filename": "logs/debug.log",
"maxBytes": 104857600,
"backupCount": 3
},
"db": {
"()": "maxlogger.MaxDBHandler",
"level": "WARNING",
"formatter": "json"
},
"queue": {
"()": "maxlogger.MaxQueueHandler",
"handlers": [
"stderr",
"file",
"db"
],
"respect_handler_level": true
}
},
"loggers": {
"root": {
"level": "DEBUG",
"handlers": [
"queue"
]
}
}
}
Есть ли что-то, что мне не хватает в использовании дополнительного атрибута? Судя по тому, что я прочитал, это должно работать довольно просто, но Я ничего не могу с этим поделать. Огромное вам спасибо за помощь в выяснении этого вопроса.
Подробнее здесь: https://stackoverflow.com/questions/786 ... the-loggin