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

Redirect to logger #21

Closed
jakirkham opened this issue Jul 27, 2018 · 2 comments · Fixed by #81
Closed

Redirect to logger #21

jakirkham opened this issue Jul 27, 2018 · 2 comments · Fixed by #81

Comments

@jakirkham
Copy link
Contributor

Would be nice to have a shim that handles redirection to Python loggers. This SO question seems relevant.

@MuellerSeb
Copy link

Something like this?

import logging
import wurlitzer

class LogCStdOutStdErr:
    """
    Context manager to redirect low-level C stdout and stderr to a logger.

    Parameters
    ----------
    logger : string, None or logging.Logger instance, optional
        Logger name for this writer. Will be the root logger by default.

    level_stdout : integer, optional
        Logging level for stdout, by default logging.INFO

    level_stderr : integer, optional
        Logging level for stderr, by default logging.WARN
    """

    def __init__(
        self, logger=None, level_stdout=logging.INFO, level_stderr=logging.WARN
    ):
        self.logger = logger.name if isinstance(logger, logging.Logger) else logger
        self.level_stdout = level_stdout
        self.level_stderr = level_stderr
        self.stdout = None
        self.stderr = None
        self.pipes = wurlitzer.pipes()

    def __enter__(self):
        self.stdout, self.stderr = self.pipes.__enter__()

    def __exit__(self, *args, **kwargs):
        self.pipes.__exit__(*args, **kwargs)
        logger = logging.getLogger(self.logger)
        for line in self.stdout.read().splitlines():
            logger.log(self.level_stdout, line)
        for line in self.stderr.read().splitlines():
            logger.log(self.level_stderr, line)

@DemonXD
Copy link

DemonXD commented Mar 9, 2023

this could not output line in time...

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.

3 participants