Saturday, November 25, 2023

Python tailing docker-compose logs

 import subprocess

def tail_docker_compose_logs(service_name=None):

    command = ['docker-compose', 'logs', '-f']

    

    if service_name:

        command.append(service_name)

    try:

        process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)


        while True:

            line = process.stdout.readline()

            if not line:

                break

            print(line.strip())


    except KeyboardInterrupt:

        # Handle Ctrl+C to gracefully stop tailing

        pass

    except subprocess.CalledProcessError as e:

        print(f"Error: {e}")


# Example usage:

tail_docker_compose_logs(service_name='web')

No comments:

Post a Comment