Settingup cloudwatch client in server
sudo aws configure
sudo yum install amazon-cloudwatch-agent
verify installation using below commands
cat ~/.aws/credentials
cat ~/.aws/config
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
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")
Reference:
Top comments (0)