aiomisc
aiomisc copied to clipboard
Extend log configuration by logging template
Hi, everyone!
I need a set plain-text format with an ordered key sequence for my application. How I can properly change the default logging template or apply my own log-handler to asyncio.entrypoint
?
Thanks!
Sorry for the long answer, but I couldn't figure out how to do it right and not break anything. A good option would be the option shown in the example below:
import os
import logging
from logging.handlers import RotatingFileHandler
from gzip import GzipFile
import aiomisc
class GzipLogFile(GzipFile):
def write(self, data) -> int:
if isinstance(data, str):
data = data.encode()
return super().write(data)
class RotatingGzipFileHandler(RotatingFileHandler):
def shouldRollover(self, record):
if not os.path.isfile(self.baseFilename):
return False
if self.stream is None:
self.stream = self._open()
return 0 < self.maxBytes < os.stat(self.baseFilename).st_size
def _open(self):
return GzipLogFile(filename=self.baseFilename, mode=self.mode)
async def main():
for _ in range(1_000):
logging.info("Hello world")
with aiomisc.entrypoint(log_config=False) as loop:
# Your custom handlers
handlers = [
logging.StreamHandler(),
RotatingGzipFileHandler(
"app.log.gz",
# 10 megabytes
maxBytes=10 * 2 ** 20,
backupCount=100
),
]
logging.basicConfig(
level=logging.INFO,
# Wrapping all handlers in separate streams will not block the
# event-loop even if gzip takes a long time to open the
# file.
handlers=map(aiomisc.log.wrap_logging_handler, handlers)
)
loop.run_until_complete(main())