### Start Example PostgreSQL Database with Docker Source: https://github.com/prometheus-community/postgres_exporter/blob/master/README.md Starts a PostgreSQL database instance using Docker for testing purposes. Ensure the POSTGRES_PASSWORD environment variable is set. ```bash docker run --net=host -it --rm -e POSTGRES_PASSWORD=password postgres ``` -------------------------------- ### ServerWithLabels Example Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/server.md Example of using ServerWithLabels to add 'cluster' and 'env' labels to metrics. ```go exporter.ServerWithLabels(prometheus.Labels{ "cluster": "primary", "env": "production", }) ``` -------------------------------- ### Example YAML Configuration File Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/config.md Provides an example of a YAML configuration file with two authentication modules, 'production' and 'staging', including their credentials and options. ```yaml auth_modules: production: type: userpass userpass: username: monitoring password: prod_secret_123 options: sslmode: require application_name: postgres_exporter staging: type: userpass userpass: username: monitoring_user password: staging_secret_456 options: sslmode: disable connect_timeout: "10" ``` -------------------------------- ### ServerWithLogger Example Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/server.md Example of using ServerWithLogger to associate a logger with the 'server' component. ```go exporter.ServerWithLogger(logger.With("component", "server")) ``` -------------------------------- ### MetricMapNamespace Example Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/types.md Demonstrates how metrics are grouped under a namespace with shared labels, showing example output for pg_stat_database. ```text pg_stat_database_xact_commit{datid="1",datname="postgres"} 12345 pg_stat_database_blks_read{datid="1",datname="postgres"} 6789 ``` -------------------------------- ### GetServer Example Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/server.md Demonstrates retrieving server instances using GetServer. Subsequent calls with the same DSN return the same instance from the pool. ```go server1, _ := servers.GetServer("postgresql://localhost/db1") server2, _ := servers.GetServer("postgresql://localhost/db1") // server1 and server2 are the same instance (from pool) ``` -------------------------------- ### Initialize Exporter with Data Sources Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/exporter.md Example showing how to retrieve data sources using GetDataSources and then initialize a new exporter instance. ```go dsns, err := exporter.GetDataSources() if err != nil { log.Fatal(err) } exporter := exporter.NewExporter(dsns, logger) ``` -------------------------------- ### Metric Caching Configuration Example Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/server.md Example of configuring metric caching with a duration of 5 minutes (300 seconds) using MetricMapNamespace. ```go // Example: cache for 5 minutes MetricMapNamespace{ cacheSeconds: 300, // 5 minutes ... } ``` -------------------------------- ### Example Usage of GetConnectionString Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/config.md Demonstrates how to obtain a connection string from a DSN and use it to open a database connection. ```go dsn := config.DSN{...} connString := dsn.GetConnectionString() db, err := sql.Open("postgres", connString) ``` -------------------------------- ### Install mixtool and jsonnetfmt Source: https://github.com/prometheus-community/postgres_exporter/blob/master/postgres_mixin/README.md Install the necessary tools for using the Postgres Mixin. These are required before building the Prometheus rules and Grafana dashboards. ```bash $ go get github.com/monitoring-mixins/mixtool/cmd/mixtool $ go get github.com/google/go-jsonnet/cmd/jsonnetfmt ``` -------------------------------- ### Add Constant Labels Example Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/exporter.md Example demonstrating how to add constant labels like 'environment' and 'service' to all metrics using WithConstantLabels. ```go exporter.WithConstantLabels("environment=production,service=api") ``` -------------------------------- ### WARN Level Logging Examples Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/errors.md Shows examples of deprecation notices and configuration warnings logged at the WARN level. ```text The extended queries.yaml config is DEPRECATED Scraping additional databases via auto discovery is DEPRECATED Constant labels on all metrics is DEPRECATED Error loading config (auth must be provided for every dsn) ``` -------------------------------- ### Example: Config File Not Found Error Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/errors.md Illustrates the error message when the specified configuration file does not exist or is not readable. ```bash $ postgres_exporter --config.file=/nonexistent/file.yml # Error: error opening config file "/nonexistent/file.yml": ... ``` -------------------------------- ### Exporter Initialization Example Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/exporter.md Demonstrates how to initialize the exporter and handle potential connection errors. Connection errors returned by NewExporter will be of type ErrorConnectToServer. ```go exporter := exporter.NewExporter(dsns, logger) // Connection errors will be of type ErrorConnectToServer ``` -------------------------------- ### Example Usage of NewExporter Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/exporter.md Demonstrates creating a new exporter with a specific DSN, logger, and custom options like metric prefix and auto-discovery. ```go logger := promslog.New(&promslog.Config{}) exporter := exporter.NewExporter( []string{"postgresql://localhost/postgres"}, logger, exporter.WithMetricPrefix("pg"), exporter.AutoDiscoverDatabases(true), ) prometheus.MustRegister(exporter) ``` -------------------------------- ### Start Exporter with Default Configuration Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/README.md Starts the postgres_exporter with a specified listen address and collection timeout. Requires the DATA_SOURCE_NAME or DATA_SOURCE_URI environment variable to be set. ```bash postgres_exporter \ --web.listen-address=":9187" \ --collection-timeout="1m" ``` -------------------------------- ### Start HTTP Server Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/main.md Starts the HTTP server for the exporter. This function blocks until the server is stopped. Ensure necessary configurations and logger are provided. ```go srv := &http.Server{} if err := web.ListenAndServe(srv, webConfig, logger); err != nil { logger.Error("Error running HTTP server", "err", err) os.Exit(1) } ``` -------------------------------- ### DEBUG Level Logging Examples Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/errors.md Shows examples of verbose, non-critical information logged at the DEBUG level. ```text Column is being forced to discard due to version incompatibility Querying namespace: pg_stat_database collector returned no data ``` -------------------------------- ### INFO Level Logging Examples Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/errors.md Provides examples of important events and non-fatal errors logged at the INFO level. ```text error querying namespace: Error retrieving rows... Semantic version changed from 13.0 to 13.2 Established new database connection ``` -------------------------------- ### Example YAML Configuration File Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/configuration.md This YAML file defines authentication modules, including username, password, and connection options like sslmode and application_name. ```yaml auth_modules: production: type: userpass userpass: username: pg_exporter password: prod_password_123 options: sslmode: require application_name: postgres_exporter staging: type: userpass userpass: username: pg_exporter password: staging_password_456 options: sslmode: allow local_dev: type: userpass userpass: username: postgres password: dev_password options: sslmode: disable connect_timeout: "5" ``` -------------------------------- ### Example Usage of CloseServers Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/exporter.md Shows how to defer the call to CloseServers to ensure database connections are properly closed when the function exits. ```go exporter := exporter.NewExporter(dsns, logger) defer exporter.CloseServers() ``` -------------------------------- ### Example connection string for postgres_exporter Source: https://github.com/prometheus-community/postgres_exporter/blob/master/README.md This is an example of the DATA_SOURCE_NAME connection string format required when running the postgres_exporter, specifying the user, password, host, port, database, and SSL mode. ```shell DATA_SOURCE_NAME=postgresql://postgres_exporter:password@localhost:5432/postgres?sslmode=disable ``` -------------------------------- ### Structured Logging Example Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/types.md Shows examples of using a structured logger (slog) for different log levels (Info, Error, Debug). This is used throughout the exporter for logging events and errors. ```go logger.Info("Connection established", "host", host) logger.Error("Query failed", "err", err) logger.Debug("Processing metrics", "count", metricCount) ``` -------------------------------- ### Example Scrape Configuration Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/config.md Shows how to configure Prometheus to scrape metrics from multiple PostgreSQL targets using a defined authentication module. ```yaml scrape_configs: - job_name: postgres_multi metrics_path: /probe params: auth_module: [production] static_configs: - targets: - prod-primary.internal:5432/postgres - prod-replica.internal:5432/postgres relabel_configs: - source_labels: [__address__] target_label: __param_target - target_label: __address__ replacement: localhost:9187 ``` -------------------------------- ### Start postgres_exporter test database with Docker Source: https://github.com/prometheus-community/postgres_exporter/blob/master/README.md This command starts a PostgreSQL database instance in a Docker container for testing purposes. It maps port 5432, sets the database name to 'circle_test', and configures the user and password. ```shell docker run -p 5432:5432 -e POSTGRES_DB=circle_test -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=test -d postgres ``` -------------------------------- ### MappingOptions Struct Initialization Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/types.md Example of initializing a MappingOptions struct, specifying column usage, description, text-to-number mappings, and supported PostgreSQL versions. ```go MappingOptions{ Usage: "MAPPEDMETRIC", Description: "Database state", Mapping: map[string]float64{ "available": 1.0, "unavailable": 0.0, }, SupportedVersions: semver.MustParseRange(">=11.0"), } ``` -------------------------------- ### Example Per-Collector Metrics Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Illustrative output showing metrics for individual collectors, including their duration and success status. ```prometheus pg_scrape_collector_duration_seconds{collector="database"} 0.005 pg_scrape_collector_success{collector="database"} 1 pg_scrape_collector_duration_seconds{collector="stat_database"} 0.008 pg_scrape_collector_success{collector="stat_database"} 1 ``` -------------------------------- ### Environment Variable Precedence Example Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/configuration.md Demonstrates how command-line flags override environment variables for configuration settings. The example shows setting a metric prefix via an environment variable and then overriding it with a CLI flag. ```bash # ENV var sets default export PG_EXPORTER_METRIC_PREFIX="pg" # CLI flag overrides ENV var postgres_exporter --metric-prefix="postgresql" # Result: metric prefix is "postgresql" ``` -------------------------------- ### Setup HTTP Handlers Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/main.md Sets up HTTP routes for serving Prometheus metrics on the configured path, providing a landing page if the metrics path is not the root, and configuring the `/probe` endpoint handler. ```go http.Handle(*metricsPath, promhttp.Handler()) if *metricsPath != "/" && *metricsPath != "" { landingPage, err := web.NewLandingPage(landingConfig) http.Handle("/", landingPage) } http.HandleFunc("/probe", handleProbe(logger, excludedDatabases)) ``` -------------------------------- ### Metrics Response Body Example Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Example of the Prometheus-format metrics returned by the /metrics endpoint. Each line is a comment or a metric. ```text # HELP pg_up Whether the last scrape of metrics from PostgreSQL was able to connect to the server # TYPE pg_up gauge pg_up 1 # HELP pg_exporter_last_scrape_duration_seconds Duration of the last scrape of metrics from PostgreSQL # TYPE pg_exporter_last_scrape_duration_seconds gauge pg_exporter_last_scrape_duration_seconds 0.042 # HELP pg_stat_database_xact_commit Number of transactions in this database that have been committed # TYPE pg_stat_database_xact_commit counter pg_stat_database_xact_commit{datid="1",datname="postgres"} 12345 ``` -------------------------------- ### Example: NewPostgresCollector with Empty DSN Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/errors.md Shows how to create a new Postgres collector and triggers an 'empty dsn' error by providing an empty DSN string. ```go collector, err := collector.NewPostgresCollector( logger, []string{}, "", // Empty DSN - will error []string{}, ) // Error: "empty dsn" ``` -------------------------------- ### Example: DSN Parsing Error Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/errors.md Demonstrates how to parse a Data Source Name (DSN) string and catch potential parsing errors. ```go dsn, err := config.dsnFromString("invalid@@dsn") if err != nil { log.Printf("Parse error: %v", err) } ``` -------------------------------- ### Initialize and Register PostgresCollector Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/collector.md Example of creating a new PostgresCollector with a specified collection timeout, excluding certain databases, and then registering it with the Prometheus registry. ```go collector, err := collector.NewPostgresCollector( logger, []string{"template0", "template1"}, "postgresql://localhost/postgres", []string{}, collector.WithCollectionTimeout("5s"), ) if err != nil { log.Fatal(err) } prometheus.MustRegister(collector) ``` -------------------------------- ### Handle Connection Error Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/types.md Example of how to check for and handle a specific connection error type during metric collection. ```go if err := exporter.Collect(ch); err != nil { if _, ok := err.(*ErrorConnectToServer); ok { log.Println("Cannot connect to PostgreSQL") } } ``` -------------------------------- ### Setup Excluded Databases Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/main.md Parses a comma-separated list of databases to exclude from metrics collection, provided via a CLI flag. Logs the list of excluded databases. ```go excludedDatabases := strings.Split(*excludeDatabases, ",") logger.Info("Excluded databases", "databases", fmt.Sprintf("%v", excludedDatabases)) ``` -------------------------------- ### Landing Page Request Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Example cURL command to access the root landing page of the Postgres Exporter. ```bash curl http://localhost:9187/ ``` -------------------------------- ### Implement a Custom Collector Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/collector.md Example of implementing a custom collector by defining a struct, a constructor, and the Update method to fetch and expose custom metrics. ```go type CustomCollector struct { logger *slog.Logger } func NewCustomCollector(config collectorConfig) (Collector, error) { return &CustomCollector{ logger: config.logger, }, nil } func (c *CustomCollector) Update( ctx context.Context, instance *instance, ch chan<- prometheus.Metric, ) error { db := instance.getDB() rows, err := db.QueryContext(ctx, "SELECT metric_name, metric_value FROM custom_metrics") if err != nil { return err } defer rows.Close() found := false for rows.Next() { found = true var name string var value float64 if err := rows.Scan(&name, &value); err != nil { return err } desc := prometheus.NewDesc( prometheus.BuildFQName("pg", "custom", name), "Custom metric", nil, nil, ) ch <- prometheus.MustNewConstMetric(desc, prometheus.GaugeValue, value) } if !found { return collector.ErrNoData } return rows.Err() } ``` -------------------------------- ### Example Bash Command for Multi-Target Probing Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/config.md Demonstrates how to use curl to probe a specific target using a named authentication module defined in the exporter's configuration. ```bash curl "http://localhost:9187/probe?target=prod-db.example.com:5432&auth_module=module_name" ``` -------------------------------- ### Fingerprint Calculation Example Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/server.md Illustrates the format of the server fingerprint, derived from the DSN, used for identification and connection pooling. ```text Fingerprint = "host:port" Examples: - localhost:5432 - db.example.com:5432 - production-rds.us-east-1.rds.amazonaws.com:5432 ``` -------------------------------- ### Prometheus Configuration for Dynamic Targets Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Example Prometheus scrape configuration demonstrating how to use the /probe endpoint with dynamic targets and relabeling. ```yaml scrape_configs: - job_name: postgres_multi metrics_path: /probe params: auth_module: [production] static_configs: - targets: - db1.example.com:5432/db1 - db2.example.com:5432/db2 - db3.example.com:5432/db3 relabel_configs: # Inject target into __param_target query param - source_labels: [__address__] target_label: __param_target # Use target value in instance label - source_labels: [__param_target] target_label: instance # Replace scrape address with exporter address - target_label: __address__ replacement: localhost:9187 ``` -------------------------------- ### PostgreSQL Exporter Main Function Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/main.md The main function initializes logging, handles configuration, retrieves data sources, creates the exporter instance, registers it with Prometheus, and starts the HTTP server. It also includes logic for a dump mode. ```go func main() { // 1. Initialize logging promslogConfig := &promslog.Config{} flag.AddFlags(kingpin.CommandLine, promslogConfig) kingpin.Parse() logger = promslog.New(promslogConfig) // 2. Handle dump mode if *onlyDumpMaps { exporter.DumpMaps() return } // 3. Load configuration if err := c.ReloadConfig(*configFile, logger); err != nil { logger.Warn("Error loading config", "err", err) } // 4. Get data sources dsns, err := exporter.GetDataSources() if err != nil { logger.Error("Failed reading data sources", "err", err.Error()) os.Exit(1) } // 5. Create exporter opts := []exporter.ExporterOpt{ exporter.DisableDefaultMetrics(*disableDefaultMetrics), exporter.AutoDiscoverDatabases(*autoDiscoverDatabases), // ... more options } exp := exporter.NewExporter(dsns, logger, opts...) defer exp.CloseServers() // 6. Register with Prometheus prometheus.MustRegister(exp) prometheus.MustRegister(collector.NewPostgresCollector(...)) // 7. Start HTTP server http.Handle(*metricsPath, promhttp.Handler()) http.HandleFunc("/probe", handleProbe(logger, excludedDatabases)) srv := &http.Server{} if err := web.ListenAndServe(srv, webConfig, logger); err != nil { logger.Error("Error running HTTP server", "err", err) os.Exit(1) } } ``` -------------------------------- ### Configure Web Listen Address Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/configuration.md Set the address and port for the exporter's HTTP server. Examples show listening on a specific port, a specific IP and port, and all available interfaces. ```bash postgres_exporter --web.listen-address=":9187" ``` ```bash postgres_exporter --web.listen-address="127.0.0.1:9187" ``` ```bash postgres_exporter --web.listen-address="0.0.0.0:9187" ``` -------------------------------- ### Setup views and functions for older PostgreSQL versions Source: https://github.com/prometheus-community/postgres_exporter/blob/master/README.md For PostgreSQL versions older than 10, this script creates a schema, necessary functions, and views to expose metrics from pg_stat_activity, pg_stat_replication, and pg_stat_statements to a non-superuser. It uses SECURITY DEFINER for functions to ensure proper permissions. ```sql CREATE SCHEMA IF NOT EXISTS postgres_exporter; GRANT USAGE ON SCHEMA postgres_exporter TO postgres_exporter; CREATE OR REPLACE FUNCTION get_pg_stat_activity() RETURNS SETOF pg_stat_activity AS $$ SELECT * FROM pg_catalog.pg_stat_activity; $$ LANGUAGE sql VOLATILE SECURITY DEFINER; CREATE OR REPLACE VIEW postgres_exporter.pg_stat_activity AS SELECT * from get_pg_stat_activity(); GRANT SELECT ON postgres_exporter.pg_stat_activity TO postgres_exporter; CREATE OR REPLACE FUNCTION get_pg_stat_replication() RETURNS SETOF pg_stat_replication AS $$ SELECT * FROM pg_catalog.pg_stat_replication; $$ LANGUAGE sql VOLATILE SECURITY DEFINER; CREATE OR REPLACE VIEW postgres_exporter.pg_stat_replication AS SELECT * FROM get_pg_stat_replication(); GRANT SELECT ON postgres_exporter.pg_stat_replication TO postgres_exporter; CREATE EXTENSION IF NOT EXISTS pg_stat_statements; CREATE OR REPLACE FUNCTION get_pg_stat_statements() RETURNS SETOF pg_stat_statements AS $$ SELECT * FROM public.pg_stat_statements; $$ LANGUAGE sql VOLATILE SECURITY DEFINER; CREATE OR REPLACE VIEW postgres_exporter.pg_stat_statements AS SELECT * FROM get_pg_stat_statements(); GRANT SELECT ON postgres_exporter.pg_stat_statements TO postgres_exporter; ``` -------------------------------- ### AuthModule Structure Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/types.md Defines the 'AuthModule' structure for handling authentication in multi-target setups. It specifies the authentication type, credentials, and additional options. ```go type AuthModule struct { Type string `yaml:"type"` UserPass UserPass `yaml:"userpass,omitempty"` Options map[string]string `yaml:"options"` } ``` -------------------------------- ### Auth Modules Configuration Example Source: https://github.com/prometheus-community/postgres_exporter/blob/master/README.md Defines authentication modules for the multi-target exporter. The 'foo1' module uses 'userpass' type with specified username, password, and connection options like sslmode. ```yaml auth_modules: foo1: # Set this to any name you want type: userpass userpass: username: first password: firstpass options: # options become key=value parameters of the DSN sslmode: disable ``` -------------------------------- ### Example SQL Query and Error Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/errors.md Illustrates a SQL query that might fail due to a non-existent column, showing the expected error message and its impact on metric emission. ```sql SELECT * FROM pg_stat_database -- Error: column "datname" does not exist in table ``` -------------------------------- ### Exporting Data Source Pass File Path Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/errors.md Example of setting the DATA_SOURCE_PASS_FILE environment variable to a non-existent path, demonstrating a data source loading error. ```bash export DATA_SOURCE_PASS_FILE=/run/secrets/nonexistent # Error: failed loading data source pass file /run/secrets/nonexistent: no such file or directory ``` -------------------------------- ### Run Postgres Exporter Locally Source: https://github.com/prometheus-community/postgres_exporter/blob/master/README.md Example command to run the postgres_exporter locally on a Debian/Ubuntu system with default settings. Ensure the DATA_SOURCE_NAME is correctly formatted for your PostgreSQL instance. ```bash sudo -u postgres DATA_SOURCE_NAME="user=postgres host=/var/run/postgresql/ sslmode=disable" postgres_exporter ``` -------------------------------- ### Custom Query Column Mapping Example Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/types.md Illustrates how to define column usage and descriptions within a custom queries.yaml file for Prometheus metric export. ```yaml queries: custom_metrics: query: SELECT status, count FROM metrics metrics: - status: usage: LABEL description: "Status value" - count: usage: GAUGE description: "Number of items" ``` -------------------------------- ### Probe Target with Auth Module Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Example of probing a PostgreSQL target using the /probe endpoint with a specified authentication module. The target includes hostname and port, and the auth_module parameter specifies credentials from the config file. ```bash curl "http://localhost:9187/probe?target=prod-db.internal:5432&auth_module=production" ``` -------------------------------- ### Multi-Target Deployment Configuration Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/README.md Sets up a multi-target deployment by defining authentication modules in a configuration file and starting the exporter. Prometheus can then be configured to scrape multiple targets using the exporter's probe endpoint. ```bash # Create config file cat > postgres_exporter.yml << 'EOF' auth_modules: production: type: userpass userpass: username: monitoring password: secret options: sslmode: require EOF # Start exporter postgres_exporter --config.file=postgres_exporter.yml # Configure Prometheus to scrape multiple targets # See: endpoints.md#get-probe (Prometheus Configuration Example) ``` -------------------------------- ### Probe Target with Full DSN Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Example of probing a PostgreSQL target using the /probe endpoint with a full DSN (Data Source Name) as the target parameter. This includes user, password, host, and database. ```bash curl "http://localhost:9187/probe?target=postgresql://user:pass@db.example.com/postgres" ``` -------------------------------- ### NewServer Constructor Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/server.md Creates a new Server instance, establishing a connection to a PostgreSQL database using a Data Source Name (DSN). Supports optional configuration options. ```go func NewServer(dsn string, opts ...ServerOpt) (*Server, error) ``` ```go server, err := exporter.NewServer( "postgresql://localhost/postgres", exporter.ServerWithLabels(prometheus.Labels{"env": "prod"}), ) if err != nil { log.Fatal(err) } defer server.Close() ``` -------------------------------- ### Initialize Logging Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/main.md Sets up structured logging for the exporter, supporting logfmt or JSON format. This ensures consistent and informative log output. ```go logger = promslog.New(promslogConfig) ``` -------------------------------- ### Create PostgreSQL Exporter Instance Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/README.md Instantiates a new PostgreSQL exporter with specified data sources, logger, and optional configurations like metric prefix and default metric disabling. This is the primary way to set up the exporter. ```go logger := promslog.New(&promslog.Config{}) exporter := exporter.NewExporter( []string{"postgresql://localhost/postgres"}, logger, exporter.WithMetricPrefix("pg"), exporter.DisableDefaultMetrics(false), ) prometheus.MustRegister(exporter) ``` -------------------------------- ### Create Exporter Instance Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/main.md Initializes the main Exporter with various configuration options, including disabling default metrics, enabling auto-discovery, setting user query paths, constant labels, excluded/included databases, and metric prefixes. Ensures resources are closed upon exit. ```go opts := []exporter.ExporterOpt{ exporter.DisableDefaultMetrics(*disableDefaultMetrics), exporter.AutoDiscoverDatabases(*autoDiscoverDatabases), exporter.WithUserQueriesPath(*queriesPath), exporter.WithConstantLabels(*constantLabelsList), exporter.ExcludeDatabases(excludedDatabases), exporter.IncludeDatabases(*includeDatabases), exporter.WithMetricPrefix(*metricPrefix), } exporter := exporter.NewExporter(dsns, logger, opts...) defer func() { exporter.CloseServers() }() ``` -------------------------------- ### ERROR Level Logging Examples Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/errors.md Illustrates significant failures requiring attention, logged at the ERROR level. ```text Error running query on database: Error scanning version string... Failed to create PostgresCollector: empty dsn Error opening connection to database: connection refused ``` -------------------------------- ### NewServers Constructor Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/server.md Initializes a new Servers pool, which can manage multiple database connections. It accepts options that will be applied to all newly created servers. ```go func NewServers(opts ...ServerOpt) *Servers ``` ```go servers := exporter.NewServers( exporter.ServerWithLogger(logger), exporter.ServerWithLabels(prometheus.Labels{"env": "production"}), ) defer servers.Close() ``` -------------------------------- ### Get Current Configuration Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/config.md Retrieves the current configuration safely. This method holds a read lock during access to ensure thread-safety. ```go func (ch *Handler) GetConfig() *Config ``` -------------------------------- ### Server Scrape Method Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/server.md Initiates metric collection for the server by querying all defined metric namespaces. Metrics are sent to the provided channel. Returns an error if any query fails. ```go func (s *Server) Scrape(ch chan<- prometheus.Metric) error ``` -------------------------------- ### Multi-Target Mode Configuration and Request Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/README.md Demonstrates how to configure authentication modules for multi-target mode using a YAML file and how to make an HTTP request to the /probe endpoint with a specified target and auth module. ```yaml auth_modules: prod: type: userpass userpass: username: monitoring password: secret options: sslmode: require ``` ```bash curl "http://localhost:9187/probe?target=db.example.com&auth_module=prod" ``` -------------------------------- ### New Configuration Handler Initialization Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/main.md Initializes a new configuration handler using the provided registerer. Panics if an error occurs during initialization. ```go func newConfigHandler() *config.Handler { handler, err := config.NewHandler(prometheus.DefaultRegisterer) if err != nil { panic(err) } return handler } ``` -------------------------------- ### NewServer Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/server.md Creates a new Server instance, establishing a connection to a PostgreSQL database using the provided Data Source Name (DSN). It supports optional configuration options for customizing the server's behavior, such as adding labels or setting a logger. ```APIDOC ## NewServer ### Description Creates a new Server connected to PostgreSQL via DSN. ### Method func NewServer(dsn string, opts ...ServerOpt) (*Server, error) ### Parameters #### Path Parameters - **dsn** (string) - Required - PostgreSQL connection string - **opts** (...ServerOpt) - Optional - Configuration options ### Response #### Success Response - **server** (*Server) - Configured server instance - **error** (error) - Connection or parsing error ### Request Example ```go server, err := exporter.NewServer( "postgresql://localhost/postgres", exporter.ServerWithLabels(prometheus.Labels{"env": "prod"}), ) if err != nil { log.Fatal(err) } defer server.Close() ``` ``` -------------------------------- ### Version Incompatibility Log Message Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/errors.md Example log message indicating that a specific metric column is being discarded due to PostgreSQL version incompatibility. ```text Column checkpointer_time_weighted is being forced to discard due to version incompatibility ``` -------------------------------- ### Probe Error: Auth Module Not Found Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Example of a 400 Bad Request response when the specified 'auth_module' is not found in the exporter's configuration. ```http GET /probe?target=db.example.com&auth_module=nonexistent HTTP/1.1 HTTP/1.1 400 Bad Request Content-Type: text/plain auth_module nonexistent not found ``` -------------------------------- ### Probe Error: Missing Target Parameter Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Example of a 400 Bad Request response when the 'target' query parameter is missing from the /probe request. ```http GET /probe HTTP/1.1 HTTP/1.1 400 Bad Request Content-Type: text/plain target is required ``` -------------------------------- ### Handling Connection Failures in Go Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/errors.md Demonstrates how connection errors are handled non-fatally in Go, ensuring the pg_up metric is 0 but other operations continue. ```go exporter := exporter.NewExporter(dsns, logger) defer exporter.CloseServers() // Connection errors are non-fatal // pg_up metric will be 0 // Other operations continue ``` -------------------------------- ### Probe Endpoint Request to Nonexistent Target Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Example request to the /probe endpoint targeting a non-existent server, which results in a 500 Internal Server Error. ```http GET /probe?target=nonexistent.example.com HTTP/1.1 ``` -------------------------------- ### Configure Multiple Postgres Instances Source: https://github.com/prometheus-community/postgres_exporter/blob/master/README.md Demonstrates how to configure the postgres_exporter to scrape multiple PostgreSQL instances by providing a comma-separated list of connection parameters in DATA_SOURCE_NAME. ```bash sudo -u postgres DATA_SOURCE_NAME="port=5432,port=6432" postgres_exporter ``` -------------------------------- ### Load Configuration Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/main.md Loads authentication modules from the specified YAML configuration file. This operation is non-fatal; the exporter continues even if configuration loading fails. ```go if err := c.ReloadConfig(*configFile, logger); err != nil { logger.Warn("Error loading config", "err", err) } ``` -------------------------------- ### GET /metrics Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Returns Prometheus-format metrics for the configured default PostgreSQL server(s). This endpoint scrapes metrics from all enabled collectors and exporter internal metrics. ```APIDOC ## GET /metrics ### Description Returns Prometheus-format metrics for the configured default PostgreSQL server(s). This endpoint scrapes metrics from all enabled collectors and exporter internal metrics. ### Method GET ### Endpoint /metrics ### Query Parameters None ### Request Body None ### Response #### Success Response (200) - **Content-Type**: text/plain; version=0.0.4 - **Body**: Plain text format metrics. Each line is either a comment (starting with `#`) or a metric. ### Request Example ```bash curl http://localhost:9187/metrics ``` ### Response Example ```text # HELP pg_up Whether the last scrape of metrics from PostgreSQL was able to connect to the server # TYPE pg_up gauge pg_up 1 # HELP pg_exporter_last_scrape_duration_seconds Duration of the last scrape of metrics from PostgreSQL # TYPE pg_exporter_last_scrape_duration_seconds gauge pg_exporter_last_scrape_duration_seconds 0.042 # HELP pg_stat_database_xact_commit Number of transactions in this database that have been committed # TYPE pg_stat_database_xact_commit counter pg_stat_database_xact_commit{datid="1",datname="postgres"} 12345 ``` ``` -------------------------------- ### Enable/Disable Collectors Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/configuration.md Individually enable or disable collectors using the --[no-]collector.{name} flags. Examples show enabling 'database' and disabling 'stat_statements'. ```bash postgres_exporter --collector.database --no-collector.stat_statements ``` -------------------------------- ### Probe Endpoint Response for Missing Credentials Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Example response when the specified auth module lacks username or password credentials, resulting in a 400 Bad Request. ```http HTTP/1.1 400 Bad Request Content-Type: text/plain auth_module invalid_module has no username or password ``` -------------------------------- ### Probe Endpoint Request with Invalid Auth Module Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Example request to the /probe endpoint when an invalid auth module is specified, leading to a 400 Bad Request. ```http GET /probe?target=db.example.com&auth_module=invalid_module HTTP/1.1 ``` -------------------------------- ### NewExporter Constructor Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/exporter.md Creates a new PostgreSQL exporter instance. Pass a list of DSNs, a logger, and optional configuration functions. ```go func NewExporter(dsn []string, logger *slog.Logger, opts ...ExporterOpt) *Exporter ``` -------------------------------- ### Probe Target with No Auth Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Example of probing a PostgreSQL target using the /probe endpoint without authentication. The target includes the hostname, port, and database name. ```bash curl "http://localhost:9187/probe?target=localhost:5432/postgres" ``` -------------------------------- ### Build PostgreSQL Exporter from Source Source: https://github.com/prometheus-community/postgres_exporter/blob/master/README.md Builds the PostgreSQL exporter executable from its source code. This involves cloning the repository, navigating to the directory, and running the make build command. ```bash git clone https://github.com/prometheus-community/postgres_exporter.git cd postgres_exporter make build ./postgres_exporter ``` -------------------------------- ### GetServer Method Signature Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/server.md Retrieves or creates a Server instance from the connection pool for a given DSN. If a server for the DSN already exists, it is returned; otherwise, a new one is created and cached. ```go func (s *Servers) GetServer(dsn string) (*Server, error) ``` -------------------------------- ### Server String Method Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/server.md Returns a string representation of the server, typically its host and port, derived from its labels. Used for identification. ```go func (s *Server) String() string ``` ```text localhost:5432 ``` -------------------------------- ### Parse and Compare Semantic Version Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/types.md Demonstrates parsing a version string and comparing it against a minimum required version using the semver library. Useful for enabling features based on PostgreSQL version. ```go version, _ := semver.ParseTolerant("13.4") if version.GE(semver.MustParse("13.0")) { // Feature available in 13+ } ``` -------------------------------- ### Create New Handler Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/config.md Instantiates a new configuration handler. Requires a Prometheus registerer for internal metrics. Returns an error if the registerer is nil. ```go func NewHandler(registerer prometheus.Registerer) (*Handler, error) ``` ```go handler, err := config.NewHandler(prometheus.DefaultRegisterer) if err != nil { log.Fatal(err) } ``` -------------------------------- ### GET /probe Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Scrapes metrics from a dynamically specified PostgreSQL target using the Prometheus multi-target pattern. This allows for dynamic target selection based on query parameters. ```APIDOC ## GET /probe ### Description Scrapes metrics from a dynamically specified PostgreSQL target. Implements the [Prometheus multi-target pattern](https://prometheus.io/docs/guides/multi-target-exporter/). ### Method GET ### Endpoint /probe ### Query Parameters - **target** (string) - Required - PostgreSQL server address. Format: `hostname:port/dbname` or `hostname/dbname` or full DSN. - **auth_module** (string) - Optional - Name of preconfigured auth module from config file. If omitted, no credentials injected. ### Request Body None ### Response #### Success Response (200) - **Content-Type**: text/plain; version=0.0.4 - **Body**: Prometheus-format metrics for the specified target, same format as `/metrics`. #### Error Response (400) - **Meaning**: Bad request - missing/invalid target or auth_module. #### Error Response (500) - **Meaning**: Server error - unable to connect to target or collect metrics. ### Request Example ```bash # Simple target with no auth curl "http://localhost:9187/probe?target=localhost:5432/postgres" # Target with auth module curl "http://localhost:9187/probe?target=prod-db.internal:5432&auth_module=production" # Full DSN as target curl "http://localhost:9187/probe?target=postgresql://user:pass@db.example.com/postgres" ``` ### Error Handling Examples: #### Missing target parameter **Request:** ``` GET /probe HTTP/1.1 ``` **Response:** ``` HTTP/1.1 400 Bad Request Content-Type: text/plain target is required ``` #### Auth module not found **Request:** ``` GET /probe?target=db.example.com&auth_module=nonexistent HTTP/1.1 ``` **Response:** ``` HTTP/1.1 400 Bad Request Content-Type: text/plain auth_module nonexistent not found ``` ``` -------------------------------- ### Prometheus Alert Rules for Postgres Exporter Errors Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/errors.md Example Prometheus alert rules to notify when the PostgreSQL instance is down, when the exporter encounters scraping errors, or when a specific collector fails. ```yaml - alert: PostgresDown expr: pg_up == 0 for: 1m - alert: PgScraperError expr: pg_exporter_last_scrape_error == 1 for: 5m - alert: PgCollectorError expr: pg_scrape_collector_success == 0 for: 5m ``` -------------------------------- ### Dump Mode Check Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/main.md Checks if the `--dumpmaps` flag is set. If true, it prints metric maps and exits without starting the server. This is useful for inspecting available metrics. ```go if *onlyDumpMaps { exporter.DumpMaps() return } ``` -------------------------------- ### Configure TLS/Authentication File Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/configuration.md Specify the path to a configuration file for TLS and authentication. The format is documented in the exporter-toolkit repository. ```bash postgres_exporter --web.config.file="/path/to/web_config.yml" ``` -------------------------------- ### Systemd Service Configuration Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/configuration.md Set up the PostgreSQL Exporter as a systemd service, specifying user, working directory, executable path, configuration file, and environment file. ```ini [Unit] Description=PostgreSQL Prometheus Exporter After=network.target [Service] Type=simple User=postgres WorkingDirectory=/opt/postgres_exporter ExecStart=/opt/postgres_exporter/postgres_exporter \ --config.file=/etc/postgres_exporter/config.yml \ --web.listen-address=":9187" \ --log.level=info EnvironmentFile=/etc/postgres_exporter/env Restart=always RestartSec=10s [Install] WantedBy=multi-user.target ``` -------------------------------- ### Reload Configuration from File Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/config.md Loads and activates a new configuration from a specified YAML file. It updates internal metrics and is safe to call multiple times. Errors during file loading or parsing are returned. ```go func (ch *Handler) ReloadConfig(f string, logger *slog.Logger) error ``` ```go err := handler.ReloadConfig("postgres_exporter.yml", logger) if err != nil { logger.Error("Failed to reload config", "err", err) } ``` -------------------------------- ### Custom Query Configuration Example Source: https://github.com/prometheus-community/postgres_exporter/wiki/Home This YAML structure defines a custom metric for the postgres_exporter. Set the PG_EXPORTER_EXTEND_QUERY_PATH environment variable to the path of this file. The 'usage' field determines how the metric is processed. ```yaml metric_name: master: true # (optional) cache_seconds: 30 # (optional) query: "SELECT metric_1, metric_2 FROM table" metrics: - metric_1: usage: "LABEL" description: "Metric 1 description" - metric_2: usage: "GAUGE" description: "Metric 2 description" ``` -------------------------------- ### Configure PostgreSQL Exporter with Multiple Data Source Names Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/configuration.md Provide a comma-separated list of PostgreSQL connection strings to the DATA_SOURCE_NAME environment variable for connecting to multiple servers. ```bash export DATA_SOURCE_NAME="postgresql://user@db1:5432/postgres,postgresql://user@db2:5432/postgres" ``` -------------------------------- ### Probe Endpoint Response for Connection Failure Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Example response when the exporter fails to connect to the target PostgreSQL server, indicated by a 500 Internal Server Error and pg_up metric set to 0. ```http HTTP/1.1 500 Internal Server Error Content-Type: text/plain; version=0.0.4 # HELP pg_up Whether the last scrape of metrics from PostgreSQL was able to connect to the server # TYPE pg_up gauge pg_up 0 ``` -------------------------------- ### Prometheus Configuration for Multi-Target Exporter Source: https://github.com/prometheus-community/postgres_exporter/blob/master/README.md Configures Prometheus to use the multi-target exporter pattern. This setup routes requests to the exporter's /probe endpoint and uses relabeling to manage targets and parameters. ```yaml scrape_configs: - job_name: 'postgres' static_configs: - targets: - server1:5432 - server2:5432 metrics_path: /probe params: auth_module: [foo] relabel_configs: - source_labels: [__address__] target_label: __param_target - source_labels: [__param_target] target_label: instance - target_label: __address__ replacement: 127.0.0.1:9116 # The postgres exporter's real hostname:port. ``` -------------------------------- ### Configure Telemetry Path Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/configuration.md Set the HTTP path where metrics will be exposed. The default is '/metrics'. ```bash postgres_exporter --web.telemetry-path="/metrics" ``` -------------------------------- ### Handling Configuration Errors in Go Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/errors.md Shows how configuration reload errors are logged, with the previous configuration remaining active and scraping continuing. ```go err := handler.ReloadConfig(configFile, logger) if err != nil { logger.Error("Failed to reload config", "err", err) // Previous configuration remains active // Scraping continues with old config } ``` -------------------------------- ### Connection Limits Configuration Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/server.md Shows the default connection limits set for each server to ensure minimal database usage and fast reconnection. ```go db.SetMaxOpenConns(1) // Only 1 active connection db.SetMaxIdleConns(1) // Keep 1 connection idle ``` -------------------------------- ### GetServer Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/server.md Retrieves or creates a Server instance for a given DSN. It utilizes a connection pool, returning an existing server if available or creating a new one if not. ```APIDOC ## GetServer ### Description Retrieves or creates a Server for the given DSN. This method implements connection pooling, returning a cached server instance if one exists for the provided DSN, otherwise creating and caching a new one. ### Method Go Function Signature ### Endpoint N/A (Go method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```go server1, _ := servers.GetServer("postgresql://localhost/db1") server2, _ := servers.GetServer("postgresql://localhost/db1") // server1 and server2 are the same instance (from pool) ``` ### Response #### Success Response - **server** (*Server) - Cached or new server instance - **error** (error) - Connection error if any occurred #### Response Example N/A (Go return values) ``` -------------------------------- ### Fetch Default Metrics Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/endpoints.md Use this command to fetch Prometheus-format metrics from the default PostgreSQL server configuration. ```bash curl http://localhost:9187/metrics ``` -------------------------------- ### Parse CLI Arguments Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/main.md Parses all command-line interface flags and sets default values for the exporter. This is the first step in the exporter's startup sequence. ```go kingpin.Version(version.Print(exporterName)) kingpin.Parse() ``` -------------------------------- ### Run unit tests for postgres_exporter Source: https://github.com/prometheus-community/postgres_exporter/blob/master/README.md This command executes the unit tests for the postgres_exporter project using the 'make test' command. ```shell make test ``` -------------------------------- ### Run PostgreSQL Exporter with Docker Source: https://github.com/prometheus-community/postgres_exporter/blob/master/README.md Runs the PostgreSQL exporter as a Docker container, connecting to a local PostgreSQL instance. Configure the DATA_SOURCE_URI, DATA_SOURCE_USER, and DATA_SOURCE_PASS environment variables. ```bash docker run \ --net=host \ -e DATA_SOURCE_URI="localhost:5432/postgres?sslmode=disable" \ -e DATA_SOURCE_USER=postgres \ -e DATA_SOURCE_PASS=password \ quay.io/prometheuscommunity/postgres-exporter ``` -------------------------------- ### Docker Deployment with Environment Variables Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/configuration.md Deploy the PostgreSQL Exporter in Docker using environment variables to configure the data source, credentials, and collection timeout. ```bash docker run \ -e DATA_SOURCE_URI="db.example.com:5432/postgres" \ -e DATA_SOURCE_USER="postgres" \ -e DATA_SOURCE_PASS="password" \ -e PG_EXPORTER_COLLECTION_TIMEOUT="30s" \ -p 9187:9187 \ quay.io/prometheuscommunity/postgres-exporter ``` -------------------------------- ### Implement Prometheus Collector Interface (Describe) Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/collector.md Describes the metrics that the collector will produce. This method implements the `prometheus.Collector` interface. ```go func (pc *ProbeCollector) Describe(ch chan<- *prometheus.Desc) ``` -------------------------------- ### Configure Custom User Queries Path Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/exporter.md Specify the path to a YAML file containing custom SQL queries for metric collection. The file format should match the internal queries.yaml structure. ```go func WithUserQueriesPath(p string) ExporterOpt ``` -------------------------------- ### ServerWithLogger Function Signature Source: https://github.com/prometheus-community/postgres_exporter/blob/master/_autodocs/api-reference/server.md Returns a ServerOpt function that configures a structured logger for the server. This allows for detailed logging of server operations. ```go func ServerWithLogger(logger *slog.Logger) ServerOpt ``` -------------------------------- ### Build Docker Image for PostgreSQL Exporter Source: https://github.com/prometheus-community/postgres_exporter/blob/master/README.md Builds the Docker image for the PostgreSQL exporter using make commands. This includes cross-compilation for different architectures and tagging the image. ```bash make promu promu crossbuild -p linux/amd64 -p linux/armv7 -p linux/arm64 -p linux/ppc64le make docker ```