logging in cloudwatch

vivekatwal

vivek atwal

Posted on July 4, 2022

logging in cloudwatch

Settingup cloudwatch client in server

sudo aws configure
sudo yum install amazon-cloudwatch-agent
Enter fullscreen mode Exit fullscreen mode

verify installation using below commands

cat ~/.aws/credentials
cat ~/.aws/config
Enter fullscreen mode Exit fullscreen mode

To check cloudwatch status using below commands or here

sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a status
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a stop
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a start

Enter fullscreen mode Exit fullscreen mode

Setting up python environment


#pip install python-json-logger
#pip install boto3
#pip install watchtower

import boto3
from pythonjsonlogger import jsonlogger
import watchtower

credentials = boto3.Session().get_credentials()
access_key = credentials.access_key
secret_key = credentials.secret_key
region = ""

cloudwatch_client = boto3.client("logs", 
region_name=region,
aws_access_key_id=access_key,
aws_secret_access_key=secret_key
)



def get_logger(log_group, logger_name):    
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.DEBUG)

    formatter = jsonlogger.JsonFormatter(fmt='%(asctime)s :: %(lineno)s :: %(levelname)-8s :: %(name)s ::  %(message)s')

    handler = watchtower.CloudWatchLogHandler(log_group_name=log_group, log_stream_name=logger_name, boto3_client=cloudwatch_client)

    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger


log_group = "app_name"
login_logger = get_logger(log_group, "login")


Enter fullscreen mode Exit fullscreen mode

Reference:

💖 💪 🙅 🚩
vivekatwal
vivek atwal

Posted on July 4, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

logging in cloudwatch
python logging in cloudwatch

July 4, 2022