28.2. 統計資訊收集器
PostgreSQL's cumulative statistics system supports collection and reporting of information about server activity. Presently, accesses to tables and indexes in both disk-block and individual-row terms are counted. The total number of rows in each table, and information about vacuum and analyze actions for each table are also counted. If enabled, calls to user-defined functions and the total time spent in each one are counted as well.
PostgreSQL also supports reporting dynamic information about exactly what is going on in the system right now, such as the exact command currently being executed by other server processes, and which other connections exist in the system. This facility is independent of the cumulative statistics system.
28.2.1. Statistics Collection Configuration
Since collection of statistics adds some overhead to query execution, the system can be configured to collect or not collect information. This is controlled by configuration parameters that are normally set in postgresql.conf
. (See Chapter 20 for details about setting configuration parameters.)
The parameter track_activities enables monitoring of the current command being executed by any server process.
The parameter track_counts controls whether cumulative statistics are collected about table and index accesses.
The parameter track_functions enables tracking of usage of user-defined functions.
The parameter track_io_timing enables monitoring of block read and write times.
The parameter track_wal_io_timing enables monitoring of WAL write times.
Normally these parameters are set in postgresql.conf
so that they apply to all server processes, but it is possible to turn them on or off in individual sessions using the SET command. (To prevent ordinary users from hiding their activity from the administrator, only superusers are allowed to change these parameters with SET
.)
Cumulative statistics are collected in shared memory. Every PostgreSQL process collects statistics locally, then updates the shared data at appropriate intervals. When a server, including a physical replica, shuts down cleanly, a permanent copy of the statistics data is stored in the pg_stat
subdirectory, so that statistics can be retained across server restarts. In contrast, when starting from an unclean shutdown (e.g., after an immediate shutdown, a server crash, starting from a base backup, and point-in-time recovery), all statistics counters are reset.
28.2.2. Viewing Statistics
Several predefined views, listed in Table 28.1, are available to show the current state of the system. There are also several other views, listed in Table 28.2, available to show the accumulated statistics. Alternatively, one can build custom views using the underlying cumulative statistics functions, as discussed in Section 28.2.24.
When using the cumulative statistics views and functions to monitor collected data, it is important to realize that the information does not update instantaneously. Each individual server process flushes out accumulated statistics to shared memory just before going idle, but not more frequently than once per PGSTAT_MIN_INTERVAL
milliseconds (1 second unless altered while building the server); so a query or transaction still in progress does not affect the displayed totals and the displayed information lags behind actual activity. However, current-query information collected by track_activities
is always up-to-date.
Another important point is that when a server process is asked to display any of the accumulated statistics, accessed values are cached until the end of its current transaction in the default configuration. So the statistics will show static information as long as you continue the current transaction. Similarly, information about the current queries of all sessions is collected when any such information is first requested within a transaction, and the same information will be displayed throughout the transaction. This is a feature, not a bug, because it allows you to perform several queries on the statistics and correlate the results without worrying that the numbers are changing underneath you. When analyzing statistics interactively, or with expensive queries, the time delta between accesses to individual statistics can lead to significant skew in the cached statistics. To minimize skew, stats_fetch_consistency
can be set to snapshot
, at the price of increased memory usage for caching not-needed statistics data. Conversely, if it's known that statistics are only accessed once, caching accessed statistics is unnecessary and can be avoided by setting stats_fetch_consistency
to none
. You can invoke pg_stat_clear_snapshot
() to discard the current transaction's statistics snapshot or cached values (if any). The next use of statistical information will (when in snapshot mode) cause a new snapshot to be built or (when in cache mode) accessed statistics to be cached.
A transaction can also see its own statistics (not yet flushed out to the shared memory statistics) in the views pg_stat_xact_all_tables
, pg_stat_xact_sys_tables
, pg_stat_xact_user_tables
, and pg_stat_xact_user_functions
. These numbers do not act as stated above; instead they update continuously throughout the transaction.
Some of the information in the dynamic statistics views shown in Table 28.1 is security restricted. Ordinary users can only see all the information about their own sessions (sessions belonging to a role that they are a member of). In rows about other sessions, many columns will be null. Note, however, that the existence of a session and its general properties such as its sessions user and database are visible to all users. Superusers and roles with privileges of built-in role pg_read_all_stats
(see also Section 22.5) can see all the information about all sessions.
Table 28.1. Dynamic Statistics Views
Table 28.2. Collected Statistics Views
The per-index statistics are particularly useful to determine which indexes are being used and how effective they are.
The pg_statio_
views are primarily useful to determine the effectiveness of the buffer cache. When the number of actual disk reads is much smaller than the number of buffer hits, then the cache is satisfying most read requests without invoking a kernel call. However, these statistics do not give the entire story: due to the way in which PostgreSQL handles disk I/O, data that is not in the PostgreSQL buffer cache might still reside in the kernel's I/O cache, and might therefore still be fetched without requiring a physical read. Users interested in obtaining more detailed information on PostgreSQL I/O behavior are advised to use the PostgreSQL statistics views in combination with operating system utilities that allow insight into the kernel's handling of I/O.
28.2.3. pg_stat_activity
pg_stat_activity
The pg_stat_activity
view will have one row per server process, showing information related to the current activity of that process.
Table 28.3. pg_stat_activity
View
pg_stat_activity
ViewNote
The wait_event
and state
columns are independent. If a backend is in the active
state, it may or may not be waiting
on some event. If the state is active
and wait_event
is non-null, it means that a query is being executed, but is being blocked somewhere in the system.
Table 28.4. Wait Event Types
Table 28.5. Wait Events of Type Activity
Activity
Table 28.6. Wait Events of Type BufferPin
BufferPin
Table 28.7. Wait Events of Type Client
Client
Table 28.8. Wait Events of Type Extension
Extension
Table 28.9. Wait Events of Type IO
IO
Table 28.10. Wait Events of Type IPC
IPC
Table 28.11. Wait Events of Type Lock
Lock
Table 28.12. Wait Events of Type LWLock
LWLock
Note
Extensions can add LWLock
types to the list shown in Table 28.12. In some cases, the name assigned by an extension will not be available in all server processes; so an LWLock
wait event might be reported as just “extension
” rather than the extension-assigned name.
Table 28.13. Wait Events of Type Timeout
Timeout
Here is an example of how wait events can be viewed:
28.2.4. pg_stat_replication
pg_stat_replication
The pg_stat_replication
view will contain one row per WAL sender process, showing statistics about replication to that sender's connected standby server. Only directly connected standbys are listed; no information is available about downstream standby servers.
Table 28.14. pg_stat_replication
View
pg_stat_replication
ViewThe lag times reported in the pg_stat_replication
view are measurements of the time taken for recent WAL to be written, flushed and replayed and for the sender to know about it. These times represent the commit delay that was (or would have been) introduced by each synchronous commit level, if the remote server was configured as a synchronous standby. For an asynchronous standby, the replay_lag
column approximates the delay before recent transactions became visible to queries. If the standby server has entirely caught up with the sending server and there is no more WAL activity, the most recently measured lag times will continue to be displayed for a short time and then show NULL.
Lag times work automatically for physical replication. Logical decoding plugins may optionally emit tracking messages; if they do not, the tracking mechanism will simply display NULL lag.
Note
The reported lag times are not predictions of how long it will take for the standby to catch up with the sending server assuming the current rate of replay. Such a system would show similar times while new WAL is being generated, but would differ when the sender becomes idle. In particular, when the standby has caught up completely, pg_stat_replication
shows the time taken to write, flush and replay the most recent reported WAL location rather than zero as some users might expect. This is consistent with the goal of measuring synchronous commit and transaction visibility delays for recent write transactions. To reduce confusion for users expecting a different model of lag, the lag columns revert to NULL after a short time on a fully replayed idle system. Monitoring systems should choose whether to represent this as missing data, zero or continue to display the last known value.
28.2.5. pg_stat_replication_slots
pg_stat_replication_slots
The pg_stat_replication_slots
view will contain one row per logical replication slot, showing statistics about its usage.
Table 28.15. pg_stat_replication_slots
View
pg_stat_replication_slots
View28.2.6. pg_stat_wal_receiver
pg_stat_wal_receiver
The pg_stat_wal_receiver
view will contain only one row, showing statistics about the WAL receiver from that receiver's connected server.
Table 28.16. pg_stat_wal_receiver
View
pg_stat_wal_receiver
View28.2.7. pg_stat_recovery_prefetch
pg_stat_recovery_prefetch
The pg_stat_recovery_prefetch
view will contain only one row. The columns wal_distance
, block_distance
and io_depth
show current values, and the other columns show cumulative counters that can be reset with the pg_stat_reset_shared
function.
Table 28.17. pg_stat_recovery_prefetch
View
pg_stat_recovery_prefetch
View28.2.8. pg_stat_subscription
pg_stat_subscription
Table 28.18. pg_stat_subscription
View
pg_stat_subscription
View28.2.9. pg_stat_subscription_stats
pg_stat_subscription_stats
The pg_stat_subscription_stats
view will contain one row per subscription.
Table 28.19. pg_stat_subscription_stats
View
pg_stat_subscription_stats
View28.2.10. pg_stat_ssl
pg_stat_ssl
The pg_stat_ssl
view will contain one row per backend or WAL sender process, showing statistics about SSL usage on this connection. It can be joined to pg_stat_activity
or pg_stat_replication
on the pid
column to get more details about the connection.
Table 28.20. pg_stat_ssl
View
pg_stat_ssl
View28.2.11. pg_stat_gssapi
pg_stat_gssapi
The pg_stat_gssapi
view will contain one row per backend, showing information about GSSAPI usage on this connection. It can be joined to pg_stat_activity
or pg_stat_replication
on the pid
column to get more details about the connection.
Table 28.21. pg_stat_gssapi
View
pg_stat_gssapi
View28.2.12. pg_stat_archiver
pg_stat_archiver
The pg_stat_archiver
view will always have a single row, containing data about the archiver process of the cluster.
Table 28.22. pg_stat_archiver
View
pg_stat_archiver
ViewNormally, WAL files are archived in order, oldest to newest, but that is not guaranteed, and does not hold under special circumstances like when promoting a standby or after crash recovery. Therefore it is not safe to assume that all files older than last_archived_wal
have also been successfully archived.
28.2.13. pg_stat_bgwriter
pg_stat_bgwriter
The pg_stat_bgwriter
view will always have a single row, containing global data for the cluster.
Table 28.23. pg_stat_bgwriter
View
pg_stat_bgwriter
View28.2.14. pg_stat_wal
pg_stat_wal
The pg_stat_wal
view will always have a single row, containing data about WAL activity of the cluster.
Table 28.24. pg_stat_wal
View
pg_stat_wal
View28.2.15. pg_stat_database
pg_stat_database
The pg_stat_database
view will contain one row for each database in the cluster, plus one for shared objects, showing database-wide statistics.
Table 28.25. pg_stat_database
View
pg_stat_database
View28.2.16. pg_stat_database_conflicts
pg_stat_database_conflicts
The pg_stat_database_conflicts
view will contain one row per database, showing database-wide statistics about query cancels occurring due to conflicts with recovery on standby servers. This view will only contain information on standby servers, since conflicts do not occur on primary servers.
Table 28.26. pg_stat_database_conflicts
View
pg_stat_database_conflicts
View28.2.17. pg_stat_all_tables
pg_stat_all_tables
The pg_stat_all_tables
view will contain one row for each table in the current database (including TOAST tables), showing statistics about accesses to that specific table. The pg_stat_user_tables
and pg_stat_sys_tables
views contain the same information, but filtered to only show user and system tables respectively.
Table 28.27. pg_stat_all_tables
View
pg_stat_all_tables
View28.2.18. pg_stat_all_indexes
pg_stat_all_indexes
The pg_stat_all_indexes
view will contain one row for each index in the current database, showing statistics about accesses to that specific index. The pg_stat_user_indexes
and pg_stat_sys_indexes
views contain the same information, but filtered to only show user and system indexes respectively.
Table 28.28. pg_stat_all_indexes
View
pg_stat_all_indexes
ViewIndexes can be used by simple index scans, “bitmap” index scans, and the optimizer. In a bitmap scan the output of several indexes can be combined via AND or OR rules, so it is difficult to associate individual heap row fetches with specific indexes when a bitmap scan is used. Therefore, a bitmap scan increments the pg_stat_all_indexes
.idx_tup_read
count(s) for the index(es) it uses, and it increments the pg_stat_all_tables
.idx_tup_fetch
count for the table, but it does not affect pg_stat_all_indexes
.idx_tup_fetch
. The optimizer also accesses indexes to check for supplied constants whose values are outside the recorded range of the optimizer statistics because the optimizer statistics might be stale.
Note
The idx_tup_read
and idx_tup_fetch
counts can be different even without any use of bitmap scans, because idx_tup_read
counts index entries retrieved from the index while idx_tup_fetch
counts live rows fetched from the table. The latter will be less if any dead or not-yet-committed rows are fetched using the index, or if any heap fetches are avoided by means of an index-only scan.
28.2.19. pg_statio_all_tables
pg_statio_all_tables
The pg_statio_all_tables
view will contain one row for each table in the current database (including TOAST tables), showing statistics about I/O on that specific table. The pg_statio_user_tables
and pg_statio_sys_tables
views contain the same information, but filtered to only show user and system tables respectively.
Table 28.29. pg_statio_all_tables
View
pg_statio_all_tables
View28.2.20. pg_statio_all_indexes
pg_statio_all_indexes
The pg_statio_all_indexes
view will contain one row for each index in the current database, showing statistics about I/O on that specific index. The pg_statio_user_indexes
and pg_statio_sys_indexes
views contain the same information, but filtered to only show user and system indexes respectively.
Table 28.30. pg_statio_all_indexes
View
pg_statio_all_indexes
View28.2.21. pg_statio_all_sequences
pg_statio_all_sequences
The pg_statio_all_sequences
view will contain one row for each sequence in the current database, showing statistics about I/O on that specific sequence.
Table 28.31. pg_statio_all_sequences
View
pg_statio_all_sequences
View28.2.22. pg_stat_user_functions
pg_stat_user_functions
The pg_stat_user_functions
view will contain one row for each tracked function, showing statistics about executions of that function. The track_functions parameter controls exactly which functions are tracked.
Table 28.32. pg_stat_user_functions
View
pg_stat_user_functions
View28.2.23. pg_stat_slru
pg_stat_slru
PostgreSQL accesses certain on-disk information via SLRU (simple least-recently-used) caches. The pg_stat_slru
view will contain one row for each tracked SLRU cache, showing statistics about access to cached pages.
Table 28.33. pg_stat_slru
View
pg_stat_slru
View28.2.24. Statistics Functions
Other ways of looking at the statistics can be set up by writing queries that use the same underlying statistics access functions used by the standard views shown above. For details such as the functions' names, consult the definitions of the standard views. (For example, in psql you could issue \d+ pg_stat_activity
.) The access functions for per-database statistics take a database OID as an argument to identify which database to report on. The per-table and per-index functions take a table or index OID. The functions for per-function statistics take a function OID. Note that only tables, indexes, and functions in the current database can be seen with these functions.
Additional functions related to the cumulative statistics system are listed in Table 28.34.
Table 28.34. Additional Statistics Functions
Warning
Using pg_stat_reset()
also resets counters that autovacuum uses to determine when to trigger a vacuum or an analyze. Resetting these counters can cause autovacuum to not perform necessary work, which can cause problems such as table bloat or out-dated table statistics. A database-wide ANALYZE
is recommended after the statistics have been reset.
pg_stat_get_activity
, the underlying function of the pg_stat_activity
view, returns a set of records containing all the available information about each backend process. Sometimes it may be more convenient to obtain just a subset of this information. In such cases, an older set of per-backend statistics access functions can be used; these are shown in Table 28.35. These access functions use a backend ID number, which ranges from one to the number of currently active backends. The function pg_stat_get_backend_idset
provides a convenient way to generate one row for each active backend for invoking these functions. For example, to show the PIDs and current queries of all backends: