Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend log configuration by logging template #78

Closed
ityshchenko opened this issue Sep 25, 2020 · 1 comment
Closed

Extend log configuration by logging template #78

ityshchenko opened this issue Sep 25, 2020 · 1 comment

Comments

@ityshchenko
Copy link

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!

@mosquito
Copy link
Collaborator

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())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants