Datadog Agent는 모니터링 중인 호스트에 직접 연결해야 합니다. 자체 호스팅 데이터베이스의 경우 127.0.0.1 또는 소켓이 선호됩니다. Agent는 pgbouncer와 같은 프록시, 로드 밸런서, 연결 풀러를 통해 데이터베이스에 연결해서는 안됩니다. Agent가 실행되는 동안 다른 호스트에 연결하는 경우(페일오버, 로드밸런싱 등) Agent는 두 호스트 간의 통계 차이를 계산하여 부정확한 메트릭을 생성합니다.
데이터 보안 고려 사항
에이전트가 데이터베이스에서 수집하는 데이터와 데이터의 보안을 유지하는 방법에 대한 자세한 내용은 민감한 정보를 참조하세요.
Postgres 설정 구성
postgresql.conf 파일에서 다음 파라미터을 설정한 다음 서버를 다시 시작해야 설정이 적용됩니다. 이러한 파라미터에 대한 자세한 내용은 Postgres 설명서를 참조하세요.
파라미터
값
설명
shared_preload_libraries
pg_stat_statements
postgresql.queries.* 메트릭에 필요합니다. pg_stat_statements 확장자를 사용하여 쿼리 메트릭 수집을 활성화합니다.
track_activity_query_size
4096
더 대규모 쿼리를 수집하는 데 필요합니다. pg_stat_activity의 SQL 텍스트의 크기를 늘립니다. 기본값으로 두면 1024자보다 긴 쿼리는 수집되지 않습니다.
pg_stat_statements.track
ALL
선택 사항. 저장 프로시저 및 함수 내에서 명령문을 추적할 수 있습니다.
pg_stat_statements.max
10000
선택 사항. pg_stat_statements에서 추적되는 정규화된 쿼리 수를 늘립니다. 이 설정은 다양한 클라이언트의 다양한 유형의 쿼리를 보는 대용량 데이터베이스에 권장됩니다.
pg_stat_statements.track_utility
off
선택 사항. PREPARE 및 EXPLAIN과 같은 유틸리티 명령을 비활성화합니다. 이 값을 off로 설정하면 SELECT, UPDATE, DELETE와 같은 쿼리만 추적됩니다.
track_io_timing
on
선택 사항. 쿼리에 대한 블록 읽기 및 쓰기 시간 수집을 활성화합니다.
에이전트에 접근 권한 부여
Datadog 에이전트가 통계와 쿼리를 수집하려면 데이터베이스에 읽기 전용 액세스가 필요합니다.
Postgres가 복제된 경우 클러스터의 기본 데이터베이스 서버(작성자)에서 다음 SQL 명령을 실행해야 합니다. 에이전트가 연결할 데이터베이스 서버에서 PostgreSQL 데이터베이스를 선택합니다. 에이전트는 연결된 데이터베이스에 관계없이 데이터베이스 서버의 모든 데이터베이스에서 텔레메트리를 수집할 수 있으므로 기본 postgres 데이터베이스를 사용하는 것이 좋습니다. 에이전트가 해당 데이터베이스 고유의 데이터에 대한 사용자 지정 쿼리를 실행하는 경우에만 다른 데이터베이스를 선택하세요.
선택한 데이터베이스를 수퍼유저(또는 충분한 권한이 있는 다른 사용자)와 연결합니다. 예를 들어 선택한 데이터베이스가 postgres면 다음을 실행하여 psql을 사용하는 postgres 사용자로 연결합니다.
추가 테이블을 쿼리해야 하는 데이터 수집 또는 커스텀 메트릭의 경우 해당 테이블에 대한 SELECT 권한을 datadog 사용자에게 부여해야 할 수도 있습니다. 예: <TABLE_NAME>에서 SELECT 권한을 Datadog에 부여합니다. 자세한 내용은 PostgreSQL 커스텀 메트릭 수집을 참조하세요.
Store your password using secret management software such as Vault. You can then reference this password as ENC[<SECRET_NAME>] in your Agent configuration files: for example, ENC[datadog_user_database_password]. See Secrets Management for more information.
The examples on this page use datadog_user_database_password to refer to the name of the secret where your password is stored. It is possible to reference your password in plain text, but this is not recommended.
확인
권한이 정확한지 확인하려면 다음 명령을 실행해 에이전트 사용자가 데이터베이스에 연결하고 코어 테이블을 읽을 수 있는지 확인합니다.
psql -h localhost -U datadog postgres -A \
-c "select * from pg_stat_database limit 1;"\
&&echo -e "\e[0;32mPostgres connection - OK\e[0m"\
||echo -e "\e[0;31mCannot connect to Postgres\e[0m"psql -h localhost -U datadog postgres -A \
-c "select * from pg_stat_activity limit 1;"\
&&echo -e "\e[0;32mPostgres pg_stat_activity read OK\e[0m"\
||echo -e "\e[0;31mCannot read from pg_stat_activity\e[0m"psql -h localhost -U datadog postgres -A \
-c "select * from pg_stat_statements limit 1;"\
&&echo -e "\e[0;32mPostgres pg_stat_statements read OK\e[0m"\
||echo -e "\e[0;31mCannot read from pg_stat_statements\e[0m"
psql -h localhost -U datadog postgres -A \
-c "select * from pg_stat_database limit 1;"\
&&echo -e "\e[0;32mPostgres connection - OK\e[0m"\
||echo -e "\e[0;31mCannot connect to Postgres\e[0m"psql -h localhost -U datadog postgres -A \
-c "select * from pg_stat_activity limit 1;"\
&&echo -e "\e[0;32mPostgres pg_stat_activity read OK\e[0m"\
||echo -e "\e[0;31mCannot read from pg_stat_activity\e[0m"psql -h localhost -U datadog postgres -A \
-c "select * from pg_stat_statements limit 1;"\
&&echo -e "\e[0;32mPostgres pg_stat_statements read OK\e[0m"\
||echo -e "\e[0;31mCannot read from pg_stat_statements\e[0m"
암호 입력 메시지가 나타나면 datadog 사용자를 생성할 때 입력한 암호를 사용합니다.
에이전트 설치
Datadog 에이전트를 설치하면 Postgres용 데이터베이스 모니터링에 필요한 Postgres 검사도 설치됩니다. Postgres 데이터베이스 호스트에 아직 에이전트를 설치하지 않았다면 에이전트 설치 지침을 참고하세요.
에이전트의 conf.d/postgres.d/conf.yaml 파일을 편집해 host/port를 가리키도록 하고, 모니터링할 호스트를 설정합니다. 사용할 수 있는 모든 설정 옵션을 보려면 postgres.d/conf.yaml 샘플을 참고하세요.
init_config:instances:- dbm:truehost:localhostport:5432username:datadogpassword:'ENC[datadog_user_database_password]'## Optional: Connect to a different database if needed for `custom_queries`# dbname: '<DB_NAME>'
init_config:instances:- dbm:truehost:localhostport:5432username:datadogpassword:'ENC[datadog_user_database_password]'pg_stat_statements_view:datadog.pg_stat_statements()pg_stat_activity_view:datadog.pg_stat_activity()## Optional: Connect to a different database if needed for `custom_queries`# dbname: '<DB_NAME>'
PostgreSQL 로깅 기본값은 stderr이며, 로그에 상세 정보를 포함하지 않습니다. 파일에 로그줄 접두사로 지정한 추가 상세 정보를 로깅하는 것이 좋습니다. 더 자세한 정보를 보려면 PostgreSQL 설명서에서 해당 토픽을 참고하세요.
/etc/postgresql/<VERSION>/main/postgresql.conf 파일에서 로깅을 설정합니다. 문 출력과 같은 정기적인 로그 결과를 보려면 로그 섹션에서 다음 파라미터의 주석 처리를 제거합니다.
logging_collector = on
log_directory = 'pg_log' # directory where log files are written,
# can be absolute or relative to PGDATA
log_filename = 'pg.log' # log file name, can include pattern
log_statement = 'all' # log all queries
#log_duration = on
log_line_prefix= '%m [%p] %d %a %u %h %c '
log_file_mode = 0644
## For Windows
#log_destination = 'eventlog'
더 자세한 기간 메트릭을 수집하여 Datadog 인터페이스에서 이를 검색할 수 있도록 하려면 문 자체와 함께 설정해야 합니다. 아래 권고 설정을 위와 비교하면 log_statement와 log_duration 옵션에서 주석 처리가 제거되었음을 알 수 있습니다. 이와 관련한 논의 내용을 보려면 여기를 참고하세요.
이 설정에서는 모든 문의 로그를 기록합니다. 특정 시간이 걸린 문만 로그하도록 출력을 줄이려면 log_min_duration_statement 값을 원하는 최소 밀리초로 설정합니다(전체 SQL 문을 로깅해도 되는지 조직 프라이버시 요구 조건을 확인하세요).
log_min_duration_statement = 0 # -1 is disabled, 0 logs all statements
# and their durations, > 0 logs only
# statements running at least this number
# of milliseconds
#log_statement = 'all'
#log_duration = on
로그 수집은 Datadog 에이전트에서 기본적으로 비활성화되어 있습니다. datadog.yaml 파일에서 활성화합니다.
logs_enabled:true
conf.d/postgres.d/conf.yaml 파일에서 다음 설정 블록을 추가 및 편집해 PostgreSQL 로그를 수집합니다.
logs:- type:filepath:"<LOG_FILE_PATH>"source:postgresqlservice:"<SERVICE_NAME>"#To handle multi line that starts with yyyy-mm-dd use the following pattern#log_processing_rules:# - type: multi_line# pattern: \d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])# name: new_log_start_with_date
service와 path 파라미터 값을 내 환경에 맞게 변경하세요. 사용할 수 있는 설정 옵션을 모두 보려면 Postgres.d/conf.yaml 샘플을 참고하세요.
It is common to configure a single Agent host to connect to multiple remote database instances (see Agent installation architectures for DBM). To connect to multiple hosts, create an entry for each host in the Postgres integration config.
Datadog recommends using one Agent to monitor no more than 30 database instances.
Benchmarks show that one Agent running on a t4g.medium EC2 instance (2 CPUs and 4GB of RAM) can successfully monitor 30 RDS db.t3.medium instances (2 CPUs and 4GB of RAM).
Use the database_autodiscovery option to permit the Agent to discover all databases on your host to monitor. You can specify include or exclude fields to narrow the scope of databases discovered. See the sample postgres.d/conf.yaml for more details.
init_config:instances:- dbm:truehost:example-service-primary.example-host.comport:5432username:datadogpassword:'ENC[datadog_user_database_password]'database_autodiscovery:enabled:true# Optionally, set the include field to specify# a set of databases you are interested in discoveringinclude:- mydb.*- example.*tags:- 'env:prod'- 'team:team-discovery'- 'service:example-service'
Running custom queries
To collect custom metrics, use the custom_queries option. See the sample postgres.d/conf.yaml for more details.
init_config:instances:- dbm:truehost:localhostport:5432username:datadogpassword:'ENC[datadog_user_database_password]'custom_queries:- metric_prefix:employeequery:SELECT age, salary, hours_worked, name FROM hr.employees;columns:- name:custom.employee_agetype:gauge- name:custom.employee_salarytype:gauge- name:custom.employee_hourstype:count- name:nametype:tagtags:- 'table:employees'
Monitoring relation metrics for multiple databases
In order to collect relation metrics (such as postgresql.seq_scans, postgresql.dead_rows, postgresql.index_rows_read, and postgresql.table_size), the Agent must be configured to connect to each database (by default, the Agent only connects to the postgres database).
Specify a single “DBM” instance to collect DBM telemetry from all databases. Use the database_autodiscovery option to avoid specifying each database name.
init_config:instances:# This instance is the "DBM" instance. It will connect to the# all logical databases, and send DBM telemetry from all databases- dbm:truehost:example-service-primary.example-host.comport:5432username:datadogpassword:'ENC[datadog_user_database_password]'database_autodiscovery:enabled:trueexclude:- ^users$- ^inventory$relations:- relation_regex:.*# This instance only collects data from the `users` database# and collects relation metrics from tables prefixed by "2022_"- host:example-service-primary.example-host.comport:5432username:datadogpassword:'ENC[datadog_user_database_password]'dbname:usersdbstrict:truerelations:- relation_regex:2022_.*relkind:- r- i# This instance only collects data from the `inventory` database# and collects relation metrics only from the specified tables- host:example-service-primary.example-host.comport:5432username:datadogpassword:'ENC[datadog_user_database_password]'dbname:inventorydbstrict:truerelations:- relation_name:products- relation_name:external_seller_products
Use the database_autodiscovery option to avoid specifying each logical database. See the sample postgres.d/conf.yaml for more details.
init_config:# This instance only collects data from the `users` database# and collects relation metrics only from the specified tablesinstances:- dbm:truehost:example-service-primary.example-host.comport:5432username:datadogpassword:'ENC[datadog_user_database_password]'dbname:usersdbstrict:truecollect_schemas:enabled:truerelations:- products- external_seller_products# This instance detects every logical database automatically# and collects relation metrics from every table- dbm:truehost:example-service–replica-1.example-host.comport:5432username:datadogpassword:'ENC[datadog_user_database_password]'database_autodiscovery:enabled:truecollect_schemas:enabled:truerelations:- relation_regex:.*
Working with hosts through a proxy
If the Agent must connect through a proxy such as the Cloud SQL Auth proxy, all telemetry is tagged with the hostname of the proxy rather than the database instance. Use the reported_hostname option to set a custom override of the hostname detected by the Agent.