Amalya E.
Amalya E.

Reputation: 91

How to set up and call 'awslogs' in docker-compose?

I have AWS EC2 with CloudWatch set up as described here.

My web server is docker-compose based one. How to it configure CloudWatch and call logging? Note: I did not set up ECS in AWS.

Upvotes: 1

Views: 749

Answers (1)

Amalya E.
Amalya E.

Reputation: 91

So i found that it's easy enough to use python's watchtower and configure my docker-compose.yml as follows:

web:
    
...
    logging:
      driver: "awslogs"
      options:
        awslogs-region: <region>
        awslogs-group: <CloudWatch group>
        awslogs-stream: <CloudWatch group stream> 

Then in you py file, add these lines:

logging.basicConfig(level=logging.INFO)

app = Flask(__name__)

try:
        session = boto3.Session(
            aws_access_key_id=os.environ['AWS_ACCESS_KEY_ID'],
            aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY'],
            region_name=os.environ['AWS_REGION']
        )
        handler = watchtower.CloudWatchLogHandler(
            boto3_session=session,
            log_group=os.environ.get('AWS_CLOUDWATCH_LOG_GROUP', "my-group"),
            stream_name=os.environ.get('AWS_CLOUDWATCH_LOG_STREAM', "my-group-stream"),
            create_log_group=False
        )
        app.logger.addHandler(handler)
except Exception as cerr:
    app.logger.error("CloudWatch logging setup failed: %s", cerr)

Then you can simply add a line like this:

app.logger.info("In root Page")

And you can see all your logs in your console's CloudWatch/LogGroups/my-group/my-group-stream

Upvotes: 2

Related Questions