Writing load balancer logs to PostgreSQL
- Prepare your cloud
- Create a cloud network
- Create a service account
- Create security groups
- Set up a database in Yandex Managed Service for PostgreSQL
- Create an instance group
- Create a log group named Yandex Cloud Logging
- Create the necessary resources in Yandex Application Load Balancer
- Create the necessary resources in Yandex Cloud Functions
- Test the load balancer and logging
- How to delete the resources you created
You can write load balancer logs (messages about each incoming request to the Yandex Application Load Balancer load balancer) to the PostgreSQL database.
To log load balancer operations, a log group will be created in Cloud Logging. Log delivery from this log group to the database will be set up using Yandex Cloud Functions resources: a trigger and a triggered function.
To create a database, we will use Yandex Managed Service for PostgreSQL.
To set up logging:
- Prepare your cloud.
- Create a cloud network.
- Create a service account.
- Create security groups.
- Set up a database in Yandex Managed Service for PostgreSQL.
- Create an instance group.
- Create a log group Yandex Cloud Logging.
- Create the required resources in Yandex Application Load Balancer.
- Create the required resources in Yandex Cloud Functions.
- Test the logging process.
If you no longer need the resources you created, delete them.
Prepare your cloud
Sign up for Yandex Cloud and create a billing account:
- Go to the management console
and log in to Yandex Cloud or create an account if you do not have one yet. - On the Yandex Cloud Billing
page, make sure you have a billing account linked and it has theACTIVE
orTRIAL_ACTIVE
status. If you do not have a billing account, create one.
If you have an active billing account, you can go to the cloud page
Learn more about clouds and folders.
Required paid resources
The support cost for a load balancer with logging includes:
- Fee for continuously running virtual machines (see Yandex Compute Cloud pricing).
- Fee for computing resources, the amount of storage and backups for a PostgreSQL cluster (see Yandex Managed Service for PostgreSQL pricing).
- Fee for function calls for log processing and computing resources allocated to execute the function (see Yandex Cloud Functions pricing).
- Fee for logging operations and log storage (see Yandex Cloud Logging pricing).
- Fee for Application Load Balancer resource usage (see Yandex Application Load Balancer pricing).
Create a cloud network
All resources you create will belong to the same cloud network.
To create a network:
- In the management console
, select Virtual Private Cloud. - Click Create network.
- Specify the Name of the network:
alb-logging-network
. - In the Advanced field, select Create subnets.
- Click Create network.
Create a service account
- In the management console
, select the appropriate folder. - In the list of services, select Identity and Access Management.
- Click Create service account.
- In the Name field, enter
alb-logging-service-account
. - Add the
functions.functionInvoker
andeditor
roles. - Click Create.
Create security groups
Security groups include rules that:
- Allow the load balancer to receive incoming traffic and redirect it to the VMs so they can receive the traffic.
- Allow the load balancer to send logs to the log group and the PostgreSQL cluster, to receive the logs from it.
You will create three security groups: one for the load balancer, another one for all VMs, and yet another for the cluster.
To create security groups:
-
In the management console
, select Virtual Private Cloud. -
Open the Security groups tab.
-
Create a security group for the load balancer:
-
Click Create security group.
-
Specify the group Name:
alb-logging-sg-balancer
. -
Select the Network:
alb-logging-network
. -
Under Rules, create the following rules using the instructions below the table:
Traffic
directionDescription Port range Protocol Source /
targetCIDR blocks Outgoing
any
All
Any
CIDR
0.0.0.0/0
Incoming
ext-http
80
TCP
CIDR
0.0.0.0/0
Incoming
ext-https
443
TCP
CIDR
0.0.0.0/0
Incoming
healthchecks
30080
TCP
Load balancer healthchecks
— -
Select the Egress or Ingress tab.
-
Click Add rule.
-
In the Port range field of the window that opens, specify a single port or a range of ports that traffic will come to or from.
-
In the Protocol field, specify the appropriate protocol or leave
Any
to allow traffic transmission over any protocol. -
In the Destination name or Source field, select the purpose of the rule:
CIDR
: Rule will apply to the range of IP addresses. In the CIDR blocks field, specify the CIDR and masks of subnets that traffic will come to or from. To add multiple CIDRs, click Add CIDR.Security group
: Rule will apply to the VMs from the current group or the selected security group.Load balancer healthchecks
: Rule allowing a load balancer to health check VMs.
-
Click Save. Repeat the steps to create all the rules from the table.
-
-
Click Save.
-
-
Similarly, create a security group for the VM named
alb-logging-sg-vms
with the samealb-logging-network
and the following rules:Traffic
directionDescription Port range Protocol Source /
targetCIDR blocks Incoming
balancer
80
TCP
Security group
alb-logging-sg-balancer
Incoming
ssh
22
TCP
CIDR
0.0.0.0/0
-
Similarly, create a security group for the PostgreSQL cluster named
alb-logging-sg-cluster
with the samealb-logging-network
and the following rules:Traffic
directionDescription Port range Protocol Source /
targetCIDR blocks Incoming
db
6432
TCP
CIDR
0.0.0.0/0
Set up a database in Yandex Managed Service for PostgreSQL
Create a cluster
Logs received from the load balancer will be written to the database that is part of the cluster Managed Service for PostgreSQL.
To create a cluster and a database:
-
In the management console
, select Managed Service for PostgreSQL. -
Click Create cluster.
-
In the Cluster name field, enter
alb-logging-cluster
. -
In the Environment field, select
PRODUCTION
. -
In the Version field, select
12
. -
Under Host class:
- Specify the
Intel Cascade Lake
platform. - Select the
burstable
type. - Specify the
b2.medium
class.
Warning
The
b2.medium
class was selected for testing only. In real projects, we do not recommend using hosts with a guaranteed vCPU share less than 100%. - Specify the
-
Under Size of storage:
- Select
network-ssd
. - Set the size to 10 GB.
Note
The type and size of the disk should be selected according to the projects to be implemented. The above values are used for testing.
- Select
-
Under Database, specify the DB attributes:
- Database name. It must be unique within the folder and contain only Latin letters, numbers, and underscores.
- DB owner username. It may only contain Latin letters, numbers, and underscores.
- User password. It must be from 8 to 128 characters long.
For the database created with the cluster, the character set and collate settings are specified as
LC_CTYPE=C
andLC_COLLATE=C
. You cannot change these settings after the database is created, but you can create a new database with the right settings. -
Under Network settings:
- Select
alb-logging-network
. - Select the
alb-logging-sg-cluster
security group.
- Select
-
Under Hosts, add a host to be accessible from outside Yandex Cloud. To do this, enable Public access.
-
Under Advanced settings, enable Access from the management console and Serverless access.
-
Leave the default values in all other fields.
-
Click Create cluster.
For more information about creating a cluster, see How to create a PostgreSQL cluster.
Afterwards, the cluster settings can be updated.
Connect to the cluster and create a table
As an example, we'll save data from the following message fields, which are logged by the load balancer when it receives requests, to the PostgreSQL database:
type
: Request protocol: HTTP or DNS.time
: Date and time of the request.http_status
: HTTP code of the load balancer's response to the request.backend_ip
: IP address of the VM that processed the request.request_processing_times.request_time
: Duration of the connection between the client and the load balancer.
You need to create a log table in advance:
After creating the cluster, you will be automatically redirected to the Clusters page.
-
Wait until
alb-logging-cluster
changes its status to Alive, then select this cluster. -
Go to the SQL tab.
-
Select the user that you created together with the cluster and enter their password.
-
Select the database you created together with the cluster and click Connect.
-
In the edit window, enter the following query:
CREATE TABLE load_balancer_requests ( type varchar(24) NOT NULL, "time" timestamptz NOT NULL, http_status varchar(4) NOT NULL, backend_ip varchar(40) NULL, request_time numeric NULL );
-
Click Execute.
-
Wait until a message confirms that the query is complete.
Create an instance group
As web servers for your website, you will use a Compute Cloud instance group. The servers will be deployed based on the LEMP stack (Linux, NGINX, MySQL, PHP). For more information, see this guide on LAMP or LEMP-based website.
To create an instance group:
-
In the management console
, select Compute Cloud. -
Open the Instance groups tab. Click Create group of virtual machines.
-
Enter the instance group name:
alb-logging-ig
. -
In the Service account field, select the account you previously created.
-
Under Allocation, select multiple availability zones to ensure fault tolerance of your hosting.
-
Under Instance template, click Define.
-
Under Boot disk image, open the Marketplace tab and click Show all Marketplace products. Select LEMP and click Use.
-
Under Computing resources:
- Select the VM's platform.
- Specify the required number of vCPUs and the amount of RAM.
This minimum configuration is enough for functional website testing:
- Platform:
Intel Cascade Lake
. - Guaranteed vCPU performance:
5%
. - vCPU:
2
. - RAM:
1 GB
.
-
Under Network settings, select the Network named
alb-logging-network
that you created earlier and its subnets. -
In the Public address field, select Auto.
-
Select the
alb-logging-sg-vms
security group created earlier. -
Specify the data required for accessing the VM:
-
Under Login, enter the username.
-
In the SSH key field, paste the contents of the public key file.
You need to create a key pair for the SSH connection yourself. See the section on how to connect to VMs via SSH.
Alert
Once created, the VM gets an IP address and a host name (FQDN) for connections. If you selected No address in the Public address field, you will not be able to access the VM from the internet.
-
-
Click Save.
-
Under Scaling, enter the Size of the instance group: 2.
-
Under Integration with Application Load Balancer, select Create target group and enter
alb-logging-tg
as the group name. You can read more about target groups here. -
Click Create.
It may take a few minutes to create an instance group. Wait until the group switches to the RUNNING
status, and all VMs in it switch to the RUNNING_ACTUAL
status.
Create a log group named Yandex Cloud Logging
- In the management console
, select the folder where you want to create your log group. - Select Cloud Logging.
- Click Create group.
- Enter a name, such as
alb-logging-group
, and description for the log group. - Set the log group record retention period.
- Click Create group.
Create the necessary resources in Yandex Application Load Balancer
Create a backend group
You must link the target group created with the VM group to the backend group that defines traffic allocation settings.
For the backends in the group, a health check will be created: the load balancer will periodically send health check requests to the VMs and expect a response for a certain period of time.
To create a backend group:
- In the management console
, select Application Load Balancer. - In the left-hand panel, select
Backend groups. Click Create backend group. - Enter the backend group Name:
alb-logging-bg
. - Under Backends, click Add.
- Enter the backend Name:
alb-logging-backend
. - In the Target groups field, select the
alb-logging-tg
group. - Specify Port backend VMs will use to receive incoming traffic from the load balancer at:
80
. - Click Add health check.
- Specify Port the backend VMs will use to accept health check connections:
80
. - Specify Path the load balancer will use for health checks:
/
. - Click Create.
Create and configure an HTTP router
The backend group should be linked to an HTTP router that defines HTTP routing rules.
To create an HTTP router:
- In the management console
, select Application Load Balancer. - In the left-hand panel, select
HTTP routers. Click Create HTTP router. - Specify the HTTP router Name:
alb-logging-router
. - Click Add virtual host.
- Specify the virtual host Name:
alb-logging-host
. - Click Add route.
- Specify the route Name:
alb-logging-route
. - In the Backend group field, select the
alb-logging-bg
group. - Click Create.
Create an L7 load balancer
To create a load balancer:
- In the management console
, select Application Load Balancer. - Click Create L7 load balancer and select Manual.
- Enter the load balancer Name:
alb-logging-balancer
. - Under Network settings, select
alb-logging-network
and thealb-logging-sg-balancer
security group that you created earlier. - Under Log settings, specify
alb-logging-group
. - Under Listeners, click Add listener.
- Enter the listener Name:
alb-logging-listener
. - In the Protocol field, select
HTTPS
. - In the HTTP router field, select the
alb-logging-router
router you created earlier. - Click Create.
Create the necessary resources in Yandex Cloud Functions
Create a function for processing data
The function will receive messages from the log group and write them to the table created earlier.
To create a function:
-
In the management console
, select Cloud Functions. -
Click Create function.
-
Enter the function name:
alb-logging-function
. -
Click Create. After creating the function, you will be automatically redirected to the Editor page.
-
Select Python 3.8 as the runtime environment and click Continue.
-
Clear the file editing area and paste the following code into it:
Function code
import os import logging import psycopg2 import json logger = logging.getLogger() logger.setLevel(logging.INFO) verboseLogging = eval(os.environ['VERBOSE_LOG']) if verboseLogging: logger.info('Loading handler function') def handler(event, context): statusCode = 500 if verboseLogging: logger.info(event) logger.info(context) connection_string = ( "host='{db_hostname}' port='{db_port}' dbname='{db_name}' " "user='{db_user}' password='{db_password}' sslmode='require'" ).format( db_hostname=os.environ['DB_HOSTNAME'], db_port=os.environ['DB_PORT'], db_name=os.environ['DB_NAME'], db_user=os.environ['DB_USER'], db_password=os.environ['DB_PASSWORD'] ) if verboseLogging: logger.info(f'Connecting: {connection_string}') conn = psycopg2.connect(connection_string) cursor = conn.cursor() messages = event['messages'][0]['details']['messages'] for message in messages: alb_message = message['json_payload'] alb_message['table_name'] = 'load_balancer_requests' insert_statement = ( 'INSERT INTO {table_name} ' '(type, "time", http_status, backend_ip, request_time) ' 'VALUES(\'{type}\', timestamptz \'{time}\', \'{http_status}\', ' '\'{backend_ip}\', {request_processing_times[request_time]});' ).format(**alb_message) if verboseLogging: logger.info(f'Exec: {insert_statement}') try: cursor.execute(insert_statement) statusCode = 200 except Exception as error: logger.error(error) conn.commit() cursor.close() conn.close() return { 'statusCode': statusCode, 'headers': { 'Content-Type': 'text/plain' } }
-
Specify the following version parameters:
- Timeout, sec:
10
. - Memory:
128 MB
.
- Timeout, sec:
-
Select the
alb-logging-service-account
service account you created earlier. On behalf of this account, the function will write data to the DB. -
Add these environment variables:
VERBOSE_LOG
: Parameter displaying detailed information about the function. Type inTrue
.DB_HOSTNAME
: Name of the PostgreSQL database host to connect to.DB_PORT
: Port for connection.DB_NAME
: Name of the database to connect to.DB_USER
: Username for the connection.DB_PASSWORD
: Password you entered when creating your cluster.
To define the values of connection parameters:
- In the management console
, select Managed Service for PostgreSQL. - Select the
alb-logging-cluster
cluster. - In the line with the database you need, click
. - Select Connect.
- On the Shell tab, find a sample connection string.
- Move the values of the
host
,port
,dbname
, anduser
variables to the appropriate Value field for the function environment variables.
-
Click Save changes.
Create a trigger
The trigger will receive copies of messages from the load balancer and pass them to the function for processing.
To create a trigger:
-
In the management console
, select the folder where you want to create a trigger. -
Select Cloud Functions.
-
In the left-hand panel, select
Triggers. -
Click Create trigger.
-
Under Basic settings:
- Enter a name for the trigger, e.g.,
alb-logging-trigger
. - In the Type field, select
Cloud Logging
. - In the Launched resource field, select
Function
.
- Enter a name for the trigger, e.g.,
-
Under Cloud Logging settings:
- In the Log group field, select
alb-logging-group
. - In the Resource types field, specify
alb.loadBalancer
.
- In the Log group field, select
-
Under Batch message settings:
- In the Waiting time, s field, specify
15
. - In the Batch size field, specify
10
.
- In the Waiting time, s field, specify
-
Under Function settings, select the function you previously created, and specify:
- Tag of the function version:
$latest
. - Service account you previously created.
- Tag of the function version:
-
Click Create trigger.
If you do not have the Yandex Cloud command line interface yet, install and initialize it.
The folder specified in the CLI profile is used by default. You can specify a different folder using the --folder-name
or --folder-id
parameter.
To create a trigger that invokes a function, run this command:
yc serverless trigger create logging alb-logging-trigger \
--log-group-name <log_group_name> \
--resource-types alb.loadBalancer \
--batch-size 10 \
--batch-cutoff 15s \
--invoke-function-name alb-logging-function \
--invoke-function-service-account-name alb-logging-service-account \
Where:
--log-group-name
: Name of the log group you previously created.--resource-types
: Log group resource types.--invoke-function-name
: Name of the function that you created earlier.--invoke-function-service-account-name
: Name of the service account created together with the function.--batch-size
: Maximum number of messages sent to the function at the same time.--batch-cutoff
: Maximum time interval between consecutive messages to the function.
For more information about the command, see the CLI reference.
Use the TriggerService/Create gRPC API call or the create REST API method.
Test the load balancer and logging
-
Get the public IP address of the load balancer:
Management console- In the management console
, select Application Load Balancer. - Find the
alb-logging-balancer
load balancer in the list and copy its IP address.
- In the management console
-
In your browser, open
http://<load_balancer_IP_address>
. Refresh the page several times. -
Make sure that the logs contain information about your requests to the load balancer:
Management console- In the management console
, select Managed Service for PostgreSQL. - Select the
alb-logging-cluster
cluster. - Go to the SQL tab.
- Select the user that you created together with the cluster and enter their password.
- Select the database you created together with the cluster, and click Connect.
- Click the
load_balancer_requests
table. You should now see the first rows of this table with your requests to the load balancer.
- In the management console
How to delete the resources you created
To shut down the load balancer and stop paying for the resources you created:
- Delete the
alb-logging-balancer
L7 load balancer. - Delete the
alb-logging-router
HTTP router. - Delete the
alb-logging-bg
backend group. - Delete the
alb-logging-ig
instance group. - Delete the
alb-logging-trigger
trigger. - Delete the
alb-logging-function
function. - Delete the
alb-logging-cluster
cluster. - Delete the
alb-logging-group
log group.