43 lines
1.3 KiB
Python
43 lines
1.3 KiB
Python
import asyncio
|
|
import logging
|
|
from contextvars import ContextVar
|
|
from time import gmtime, strftime
|
|
|
|
import aiofiles
|
|
|
|
request_id_ctx: ContextVar[str] = ContextVar("request_id", default="-")
|
|
message_id_ctx: ContextVar[str] = ContextVar("message_id", default="-")
|
|
|
|
log_queue=asyncio.Queue()
|
|
|
|
class LogWriter:
|
|
def __init__(self) -> None:
|
|
pass
|
|
|
|
async def log_writer(self)->None:
|
|
while True:
|
|
log_type, msg=await log_queue.get()
|
|
await self._write(msg, log_type)
|
|
|
|
async def _write(self, msg:str, type:str)->None:
|
|
file_time = strftime("%b_%Y", gmtime())
|
|
current_time = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
|
|
|
|
async with aiofiles.open(f"./logs/{type}_log_{file_time}.txt", "a") as f:
|
|
await f.write(f"[{current_time}] {msg}\n")
|
|
|
|
|
|
class LoggerDB(logging.Handler):
|
|
|
|
def emit(self, record: logging.LogRecord) -> None:
|
|
msg = self.format(record)
|
|
rid=request_id_ctx.get()
|
|
log_queue.put_nowait(("sql",f"[{rid}] {msg}"))
|
|
|
|
|
|
class LoggerDaemon(logging.Handler):
|
|
|
|
def emit(self, record: logging.LogRecord)->None:
|
|
msg= self.format(record)
|
|
mid=message_id_ctx.get()
|
|
log_queue.put_nowait(("daemon", f"[{mid}], {msg}")) |