Lax_Sam
Lax_Sam

Reputation: 1139

How to log the output of sys.stdout using watchtower?

I have created one logger using logging module and another one using watchtower. Now the watchtower log is a superset of the log created using logging module. So whatever is logged in logging_logger should also be logged in watchtower_logger. I am logging the output of sys.stdout in logging_logger. Below is the implementation.

import logging 
import sys
import watchtower

def setup_logging_logger(
    name="Logging Logger",
    level=logging.INFO,
):
    logger = logging.getLogger(name)
    logger.setLevel(level)

    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.setFormatter(log_format)
    stdout_handler.setLevel(level)
    logger.addHandler(stdout_handler)

    return logger


def setup_watchtower_logger(
    name="Watchtower Logger", 
    level=logging.INFO
):
    logger = logging.getLogger(name)
    logger.setLevel(level)

    cloudwatch_config = {
        "boto3_client": boto3_logs_client,
        "log_group_name": log_group_name,
        "log_stream_name": log_stream_name,
    }
    cloudwatch_handler = watchtower.CloudWatchLogHandler(
        **cloudwatch_config, stream=sys.stdout
    )
    cloudwatch_handler.setFormatter(log_format)
    cloudwatch_handler.setLevel(level)
    logger.addHandler(cloudwatch_handler)

    return logger


logging_logger = setup_logging_logger()
watchtower_logger = setup_watchtower_logger()

How can I log sys.stdout in watchtower_logger? Or is there a better way to create a hierarchy of loggers in python?

Upvotes: 0

Views: 42

Answers (0)

Related Questions