"""
This log configuration file ensures that all output written to the console by any Python script is also captured and stored in the "project_log.log" file.

"""

import logging
import sys

class StreamToLogger:
    def __init__(self, logger, log_level=logging.INFO, stream=None):
        self.logger = logger
        self.log_level = log_level
        self.stream = stream  # Original stream (stdout or stderr)

    def write(self, buf):
        try:
            if buf.rstrip():
                self.stream.write(buf)  # Write to the original stream
                self.stream.flush()  # Ensure the buffer is flushed immediately
                for line in buf.rstrip().splitlines():
                    self.logger.log(self.log_level, line.rstrip())
        except Exception as e:
            self.logger.error("Failed to log or write to stream: {}".format(str(e)))

    def flush(self):
        try:
            self.stream.flush()
        except Exception as e:
            self.logger.error("Failed to flush the stream: {}".format(str(e)))

def setup_logging():
    # Configure logging
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s:%(levelname)s:%(message)s',
        filename="project_log.log",
        filemode='a'
    )

    # Replace stdout and stderr with logging to both file and console
    sys.stdout = StreamToLogger(logging.getLogger('STDOUT'), logging.INFO, sys.stdout)
    sys.stderr = StreamToLogger(logging.getLogger('STDERR'), logging.ERROR, sys.stderr)
