TigerData logo
TigerData logo
  • Product

    Tiger Cloud

    Robust elastic cloud platform for startups and enterprises

    Agentic Postgres

    Postgres for Agents

    TimescaleDB

    Postgres for time-series, real-time analytics and events

  • Docs
  • Pricing

    Pricing

    Enterprise Tier

  • Developer Hub

    Changelog

    Benchmarks

    Blog

    Community

    Customer Stories

    Events

    Support

    Integrations

    Launch Hub

  • Company

    Contact us

    About

    Timescale

    Partners

    Security

    Careers

Log InTry for free
Home
Alternatives to TimescaleTime-Series Analysis in RAWS Time-Series Database: Understanding Your OptionsWhat Is a Time Series and How Is It Used?Is Your Data Time Series? Data Types Supported by PostgreSQL and TimescaleWhy Consider Using PostgreSQL for Time-Series Data?How to Work With Time Series in Python?Tools for Working With Time-Series Analysis in PythonGuide to Time-Series Analysis in PythonTime-Series Analysis and Forecasting With Python Understanding Database Workloads: Variable, Bursty, and Uniform PatternsThe Best Time-Series Databases ComparedUnderstanding Autoregressive Time-Series ModelingStationary Time-Series AnalysisCreating a Fast Time-Series Graph With Postgres Materialized ViewsWhat Are Open-Source Time-Series Databases—Understanding Your OptionsWhat Is Temporal Data?
Optimizing Your Database: A Deep Dive into PostgreSQL Data TypesHow to Install PostgreSQL on LinuxHow to Install PostgreSQL on MacOS5 Common Connection Errors in PostgreSQL and How to Solve ThemHow to Fix No Partition of Relation Found for Row in Postgres DatabasesHow to Fix Transaction ID Wraparound ExhaustionUnderstanding PostgreSQL Date and Time FunctionsData Partitioning: What It Is and Why It MattersWhat Is Data Compression and How Does It Work?Self-Hosted or Cloud Database? A Countryside Reflection on Infrastructure ChoicesUnderstanding ACID Compliance Understanding percentile_cont() and percentile_disc() in PostgreSQLUsing PostgreSQL UPDATE With JOINUnderstanding PostgreSQL Conditional FunctionsUnderstanding PostgreSQL Array FunctionsWhat Characters Are Allowed in PostgreSQL Strings?Understanding PostgreSQL's COALESCE FunctionWhat Is Data Transformation, and Why Is It Important?Understanding PostgreSQL User-Defined FunctionsStructured vs. Semi-Structured vs. Unstructured Data in PostgreSQLUnderstanding SQL Aggregate FunctionsUnderstanding Foreign Keys in PostgreSQLUnderstanding PostgreSQLUnderstanding FROM in PostgreSQL (With Examples)Understanding FILTER in PostgreSQL (With Examples)How to Address ‘Error: Could Not Resize Shared Memory Segment’ Understanding HAVING in PostgreSQL (With Examples)Understanding GROUP BY in PostgreSQL (With Examples)Understanding LIMIT in PostgreSQL (With Examples)Understanding PostgreSQL FunctionsUnderstanding ORDER BY in PostgreSQL (With Examples)Understanding WINDOW in PostgreSQL (With Examples)Understanding PostgreSQL WITHIN GROUPPostgreSQL Mathematical Functions: Enhancing Coding EfficiencyUnderstanding DISTINCT in PostgreSQL (With Examples)Using PostgreSQL String Functions for Improved Data AnalysisData Processing With PostgreSQL Window FunctionsUnderstanding WHERE in PostgreSQL (With Examples)PostgreSQL Joins : A SummaryUnderstanding OFFSET in PostgreSQL (With Examples)Understanding the Postgres string_agg FunctionWhat Is a PostgreSQL Full Outer Join?What Is a PostgreSQL Cross Join?What Is a PostgreSQL Inner Join?What Is a PostgreSQL Left Join? And a Right Join?PostgreSQL Join Type TheoryUnderstanding PostgreSQL SELECTA Guide to PostgreSQL ViewsStrategies for Improving Postgres JOIN PerformanceUnderstanding the Postgres extract() FunctionUnderstanding the rank() and dense_rank() Functions in PostgreSQL
Top PostgreSQL Drivers for PythonPostgreSQL Performance Tuning: Optimizing Database IndexesDetermining the Optimal Postgres Partition SizeBest Practices for (Time-)Series Metadata Tables Guide to Postgres Data ManagementHow to Query JSONB in PostgreSQLHow to Index JSONB Columns in PostgreSQLHow to Monitor and Optimize PostgreSQL Index PerformanceOptimizing Array Queries With GIN Indexes in PostgreSQLSQL/JSON Data Model and JSON in SQL: A PostgreSQL PerspectiveHow to Query JSON Metadata in PostgreSQLA Guide to pg_restore (and pg_restore Example)Handling Large Objects in PostgresPostgreSQL Performance Tuning: Designing and Implementing Your Database SchemaGuide to PostgreSQL PerformancePostgreSQL Performance Tuning: Key ParametersHow to Reduce Bloat in Large PostgreSQL TablesGuide to PostgreSQL Database OperationsPostgreSQL Performance Tuning: How to Size Your DatabaseExplaining PostgreSQL EXPLAINA Guide to Data Analysis on PostgreSQLHow PostgreSQL Data Aggregation WorksBuilding a Scalable DatabaseA Guide to Scaling PostgreSQLPg_partman vs. Hypertables for Postgres PartitioningHow to Use PostgreSQL for Data TransformationWhen to Consider Postgres PartitioningDesigning Your Database Schema: Wide vs. Narrow Postgres TablesRecursive Query in SQL: What It Is, and How to Write OneGuide to PostgreSQL Database DesignWhat Is Audit Logging and How to Enable It in PostgreSQLGuide to PostgreSQL SecurityNavigating Growing PostgreSQL Tables With Partitioning (and More)An Intro to Data Modeling on PostgreSQLBest Practices for Time-Series Data Modeling: Single or Multiple Partitioned Table(s) a.k.a. Hypertables What Is a PostgreSQL Temporary View?A PostgreSQL Database Replication GuideUnderstanding PostgreSQL TablespacesHow to Compute Standard Deviation With PostgreSQLHow to Use Psycopg2: The PostgreSQL Adapter for Python
Best Practices for Scaling PostgreSQLBest Practices for PostgreSQL Database OperationsHow to Store Video in PostgreSQL Using BYTEAHow to Handle High-Cardinality Data in PostgreSQLHow to Use PostgreSQL for Data NormalizationTesting Postgres Ingest: INSERT vs. Batch INSERT vs. COPYBest Practices for Postgres SecurityBest Practices for Postgres Data ManagementBest Practices for Postgres PerformanceHow to Design Your PostgreSQL Database: Two Schema ExamplesHow to Manage Your Data With Data Retention PoliciesBest Practices for PostgreSQL Data AnalysisBest Practices for PostgreSQL AggregationBest Practices for Postgres Database ReplicationHow to Use a Common Table Expression (CTE) in SQL
PostgreSQL Extensions: Unlocking Multidimensional Points With Cube PostgreSQL Extensions: hstorePostgreSQL Extensions: ltreePostgreSQL Extensions: pg_prewarmPostgreSQL Extensions: pgRoutingPostgreSQL Extensions: Using PostGIS and Timescale for Advanced Geospatial InsightsPostgreSQL Extensions: Turning PostgreSQL Into a Vector Database With pgvectorPostgreSQL Extensions: amcheckPostgreSQL Extensions: Secure Your Time-Series Data With pgcryptoPostgreSQL Extensions: pg_stat_statementsPostgreSQL Extensions: Database Testing With pgTAPPostgreSQL Extensions: Install pg_trgm for Data MatchingPostgreSQL Extensions: PL/pgSQLPostgreSQL Extensions: Intro to uuid-ossp
PostgreSQL as a Real-Time Analytics DatabaseHow to Build an IoT Pipeline for Real-Time Analytics in PostgreSQLHow to Choose a Real-Time Analytics DatabaseUnderstanding OLTPOLAP Workloads on PostgreSQL: A GuideHow to Choose an OLAP DatabaseData Analytics vs. Real-Time Analytics: How to Pick Your Database (and Why It Should Be PostgreSQL)What Is the Best Database for Real-Time AnalyticsColumnar Databases vs. Row-Oriented Databases: Which to Choose?
A Brief History of AI: How Did We Get Here, and What's Next?Text-to-SQL: A Developer’s Zero-to-Hero GuideA Beginner’s Guide to Vector EmbeddingsPostgreSQL as a Vector Database: A Pgvector TutorialUsing Pgvector With PythonHow to Choose a Vector DatabaseVector Databases Are the Wrong AbstractionUnderstanding DiskANNStreaming DiskANN: How We Made PostgreSQL as Fast as Pinecone for Vector DataA Guide to Cosine SimilarityImplementing Cosine Similarity in PythonVector Database Basics: HNSWVector Database Options for AWSVector Store vs. Vector Database: Understanding the ConnectionPgvector vs. Pinecone: Vector Database Performance and Cost ComparisonHow to Build LLM Applications With Pgvector Vector Store in LangChainHow to Implement RAG With Amazon Bedrock and LangChainRetrieval-Augmented Generation With Claude Sonnet 3.5 and PgvectorPostgreSQL Hybrid Search Using Pgvector and CohereWhat Is Vector Search? Vector Search vs Semantic SearchNearest Neighbor Indexes: What Are IVFFlat Indexes in Pgvector and How Do They WorkRAG Is More Than Just Vector SearchImplementing Filtered Semantic Search Using Pgvector and JavaScriptRefining Vector Search Queries With Time Filters in Pgvector: A TutorialUnderstanding Semantic SearchBuilding an AI Image Gallery With OpenAI CLIP, Claude Sonnet 3.5, and PgvectorWhen Should You Use Full-Text Search vs. Vector Search?HNSW vs. DiskANN
Understanding IoT (Internet of Things)Storing IoT Data: 8 Reasons Why You Should Use PostgreSQLHow to Choose an IoT DatabaseHow to Simulate a Basic IoT Sensor Dataset on PostgreSQLFrom Ingest to Insights in Milliseconds: Everactive's Tech Transformation With TimescaleHow Ndustrial Is Providing Fast Real-Time Queries and Safely Storing Client Data With 97 % CompressionA Beginner’s Guide to IIoT and Industry 4.0Why You Should Use PostgreSQL for Industrial IoT DataHow Hopthru Powers Real-Time Transit Analytics From a 1 TB Table Migrating a Low-Code IoT Platform Storing 20M Records/DayMoving Past Legacy Systems: Data Historian vs. Time-Series DatabaseHow United Manufacturing Hub Is Introducing Open Source to ManufacturingBuilding IoT Pipelines for Faster Analytics With IoT CoreVisualizing IoT Data at Scale With Hopara and TimescaleDB
What Is ClickHouse and How Does It Compare to PostgreSQL and TimescaleDB for Time Series?Timescale vs. Amazon RDS PostgreSQL: Up to 350x Faster Queries, 44 % Faster Ingest, 95 % Storage Savings for Time-Series DataWhat We Learned From Benchmarking Amazon Aurora PostgreSQL ServerlessTimescaleDB vs. Amazon Timestream: 6,000x Higher Inserts, 5-175x Faster Queries, 150-220x CheaperHow to Store Time-Series Data in MongoDB and Why That’s a Bad IdeaPostgreSQL + TimescaleDB: 1,000x Faster Queries, 90 % Data Compression, and Much MoreEye or the Tiger: Benchmarking Cassandra vs. TimescaleDB for Time-Series Data
Alternatives to RDSWhy Is RDS so Expensive? Understanding RDS Pricing and CostsEstimating RDS CostsHow to Migrate From AWS RDS for PostgreSQL to TimescaleAmazon Aurora vs. RDS: Understanding the Difference
What InfluxDB Got Wrong5 InfluxDB Alternatives for Your Time-Series Data8 Reasons to Choose Timescale as Your InfluxDB Alternative InfluxQL, Flux, and SQL: Which Query Language Is Best? (With Cheatsheet)TimescaleDB vs. InfluxDB: Purpose Built Differently for Time-Series Data
How to Migrate Your Data to Timescale (3 Ways)Postgres TOAST vs. Timescale CompressionBuilding Python Apps With PostgreSQL: A Developer's GuideMore Time-Series Data Analysis, Fewer Lines of Code: Meet HyperfunctionsTimescale Tips: Testing Your Chunk SizeIs Postgres Partitioning Really That Hard? An Introduction To HypertablesPostgreSQL Materialized Views and Where to Find Them5 Ways to Monitor Your PostgreSQL DatabaseData Visualization in PostgreSQL With Apache Superset
Postgres cheat sheet
HomeTime series basicsPostgres basicsPostgres guidesPostgres best practicesPostgres extensionsPostgres for real-time analytics
Sections

Performance

Schema design

PostgreSQL Performance Tuning: Designing and Implementing Your Database Schema
Guide to PostgreSQL Performance

Performance tuning

PostgreSQL Performance Tuning: Key ParametersPostgreSQL Performance Tuning: Optimizing Database IndexesHow to Reduce Bloat in Large PostgreSQL TablesPostgreSQL Performance Tuning: How to Size Your Database

Partitioning

Determining the Optimal Postgres Partition SizeNavigating Growing PostgreSQL Tables With Partitioning (and More)When to Consider Postgres PartitioningPg_partman vs. Hypertables for Postgres Partitioning

Database design and modeling

An Intro to Data Modeling on PostgreSQLDesigning Your Database Schema: Wide vs. Narrow Postgres TablesBest Practices for Time-Series Data Modeling: Single or Multiple Partitioned Table(s) a.k.a. Hypertables Best Practices for (Time-)Series Metadata Tables Guide to PostgreSQL Database Design

Database replication

A PostgreSQL Database Replication Guide

Data management

Understanding PostgreSQL TablespacesGuide to Postgres Data ManagementHandling Large Objects in Postgres

Data aggregation

How PostgreSQL Data Aggregation Works

Scaling postgres

Building a Scalable DatabaseA Guide to Scaling PostgreSQL

Database tools and libraries

How to Use Psycopg2: The PostgreSQL Adapter for PythonTop PostgreSQL Drivers for Python

Database operations

Guide to PostgreSQL Database Operations

JSON

How to Query JSONB in PostgreSQLHow to Index JSONB Columns in PostgreSQLSQL/JSON Data Model and JSON in SQL: A PostgreSQL PerspectiveHow to Query JSON Metadata in PostgreSQL

Database indexes

How to Monitor and Optimize PostgreSQL Index Performance

Query optimization

Explaining PostgreSQL EXPLAINWhat Is a PostgreSQL Temporary View?Optimizing Array Queries With GIN Indexes in PostgreSQLRecursive Query in SQL: What It Is, and How to Write One

Database backups and restore

A Guide to pg_restore (and pg_restore Example)

Data analysis

A Guide to Data Analysis on PostgreSQLHow to Compute Standard Deviation With PostgreSQL

Data transformation

How to Use PostgreSQL for Data Transformation

Database security

What Is Audit Logging and How to Enable It in PostgreSQLGuide to PostgreSQL Security

Products

Time Series and Analytics AI and Vector Enterprise Plan Cloud Status Support Security Cloud Terms of Service

Learn

Documentation Blog Forum Tutorials Changelog Success Stories Time Series Database

Company

Contact Us Careers About Brand Community Code Of Conduct Events

Subscribe to the Tiger Data Newsletter

By submitting, you acknowledge Tiger Data's Privacy Policy

2025 (c) Timescale, Inc., d/b/a Tiger Data. All rights reserved.

Privacy preferences
LegalPrivacySitemap

Published at Jul 10, 2024

What Is Audit Logging and How to Enable It in PostgreSQL

Try for free

Start supercharging your PostgreSQL today.

A detective elephant looking through a magnifying glass to inspect those audit logs.

Written by Ana Tavares, Sarah Conway, and Doug Ortiz

Every developer working with customer data—especially sensitive data—knows that maintaining stringent security and compliance standards is critical. Among various measures, database audit logging plays a vital role in adding an extra layer of security. 

Audit logging, also known as auditing or audit trail logging, is the process of recording a detailed log of all activities and transactions performed within a system or application, particularly focusing on access and changes to data. In the context of databases, it involves tracking and documenting every action that occurs. 

If you’re a PostgreSQL user, one of the most effective ways to do audit logging is using pgAudit. This open-source extension for PostgreSQL enables detailed logging of database operations. In this blog post, we’ll explain why audit logging is crucial and how to do it in PostgreSQL using pgAudit. 

The pgAudit extension is now available to all Timescale Cloud customers directly within the Timescale console, providing detailed database session and/or object audit logging in the Timescale logs. Otherwise, we’ll walk you through installing pgAudit on your local installation later on in this article. Keep reading for more information!

What Is the Difference Between Audit Logging and an Activity Log?

The terms "audit log" and "activity log" are often used interchangeably, but they have distinct differences in terms of their focus, purpose, and content.

Audit logs are primarily used to ensure security, maintain compliance with regulations, and provide a verifiable record of actions. They are designed to track who did what, when, and how in detail. They also ensure that every action taken by users or administrators is recorded, providing a trail that can be audited to hold individuals accountable.

On the other hand, activity logs are used to monitor a system's normal operations, tracking user activities and system events to understand system health, behavior, and performance. They additionally provide insights into how users interact with the system, which can help improve user experience and optimize system performance.

What about database audit logging?

Database audit logging involves recording the actions performed on the database. Many organizations operate under strict security policies that mandate logging all operations at the database level. In PostgreSQL (and TimescaleDB), this includes but is not limited to, SQL queries, data modifications, and login attempts. Database audit logging helps monitor user activities, detect suspicious actions, and ensure compliance with regulations such as GDPR, HIPAA, and others. 

If you’re a PostgreSQL (or TimescaleDB) user, the open-source extension pgAudit helps fulfill these requirements by providing a detailed audit trail of database activities. This is particularly crucial for industries subject to rigid regulatory standards, such as healthcare, finance, and government sectors.

This is exactly the case here at Timescale, where we now provide pgAudit support to serve cloud customers who have stricter security and compliance requirements, such as the need to log all operations done at the database level. As an example, integrating pgAudit directly into our UI is a significant step for us toward delivering HIPAA support because the extension’s detailed logging capabilities ensure that all database interactions are recorded. This provides the necessary audit trails required for HIPAA compliance.

Key Components of Audit Logging

To provide a chronological record of events that can be used for security monitoring, compliance, troubleshooting, and performance analysis, audit logging includes the following key components:

  1. Event capture: Audit logs capture specific events, such as user logins, logouts, SQL queries, data changes, and modifications to the database schema.

  2. Timestamping: Each logged event is associated with a precise timestamp, indicating when the event occurred.

  3. User identification: Logs include information about the user who performed the action, providing accountability and traceability.

  4. Action details: The logs detail the nature of the action. This includes the type of operation (e.g., SELECT, INSERT, UPDATE, DELETE), the affected data or objects, and the outcome of the action.

  5. Contextual information: Additional context, such as the source IP address, application name, and session ID, may be recorded to provide a comprehensive understanding of the event.

In short, these are the components that will be kept in your PostgreSQL audit table. Now, let’s see how you can create it using pgAudit.

PgAudit: The PostgreSQL Audit Extension

PgAudit is a PostgreSQL extension that allows administrators to audit database activities at both the session and object levels. Since our goal is to save developers’ time, we’ll first show you how to easily enable it in Timescale Cloud (you can create a free account and take it for a spin for 30 days to try our automated data partitioning, hybrid row-columnar storage, incremental up-to-date materializations, and advanced data compression techniques).

If you don’t mind the added work, we’ll then show you how to configure it in vanilla PostgreSQL or self-hosted TimescaleDB.

How to enable and configure pgAudit in Timescale Cloud

Enabling and configuring pgAudit in your Timescale database is straightforward. The default configuration parameters require superuser access and can be set through the Timescale service interface. Follow these steps to configure pgAudit:

Step 1: Access database parameters 

Click on the Services link on the left-hand navigation.

image

Click on the service you wish to configure.

image

Navigate to the Service information section in your Timescale interface.

image

Click on the Operations tab, followed by the Database Parameters link on the left-hand Operations navigation, and finally, the Advanced Parameters tab on the Database parameters section.

imageimageimage

Step 2: Configure pgAudit

Search for the ‘pgaudit’ extension in the Database parameters list.

Add the values you want to set in the ‘pgaudit.log’ and ‘pgaudit.log_client' common parameters.

image

For detailed instructions and configuration options, check the pgAudit documentation.

To maximize the utility of your audit logs, you can export them to CloudWatch. This allows you to retain the logs for extended periods and leverage CloudWatch's monitoring and alerting capabilities. This blog post will guide you on integrating Amazon CloudWatch with your Timescale service.

How to enable pgAudit in PostgreSQL on Linux

In this section, we’ll cover:

  • Installing pgaudit

  • Setting up your environment

  • Configuring pgaudit for the first time

Step 1: Install PostgreSQL and development tools

First, ensure you have PostgreSQL and the necessary development tools installed on your system.

For Ubuntu/Debian:

sudo apt-get update sudo apt-get install postgresql postgresql-contrib postgresql-server-dev-all

For CentOS/RHEL:

sudo yum install postgresql-server postgresql-contrib postgresql-devel Afterward, verify your PostgreSQL installation by checking the current psql version.

psql -V You should see a result similar to the following:

psql (PostgreSQL) 16.3 (Ubuntu 16.3-0ubuntu0.24.04.1)

Step 2: Install pgaudit

The pgaudit extension might be available through your package manager. Alternatively, you can compile it from source.

Installing via Package Manager

For Ubuntu/Debian:

sudo apt-get install postgresql-XX-pgaudit  # replace XX with your PostgreSQL version

For CentOS/RHEL:

sudo yum install pgaudit

Step 3: Configure PostgreSQL

1. Edit postgresql.conf: Locate the postgresql.conf file, usually found in the PostgreSQL data directory. 

As the root user, add or modify the following configuration settings:

shared_preload_libraries = 'pgaudit'

Optionally, you can add more pgaudit configurations like:

pgaudit.log = 'all, -misc'

More configurations can be found within the official pgAudit documentation.

2. Restart PostgreSQL: Restart the PostgreSQL service to apply the changes.

sudo systemctl restart postgresql

Step 4: Create the extension in the database

1. Connect to your PostgreSQL instance:

   sudo -su postgres    psql

2. Create the extension in the desired database:    CREATE EXTENSION pgaudit;    

Step 5: Verify installation

To verify that pgaudit is installed and configured correctly, you can run the following query:

SELECT * FROM pg_extension WHERE extname = 'pgaudit';

Or alternatively, use the shortcut:

\dx pgaudit

You should see an entry for pgaudit.

Additional Configuration (Optional): Logging different activities

You can configure pgaudit to log different types of activities. For example:

ALTER SYSTEM SET pgaudit.log = 'read, write';

After making changes to postgresql.conf or using ALTER SYSTEM, always remember to reload or restart PostgreSQL as your system user. sudo systemctl reload postgresql

Example use case: Logging SELECT statements

Here's an example of how you might use pgaudit to log SELECT statements on a specific table:

1. Enable auditing for a specific table:

CREATE TABLE example_table (id serial PRIMARY KEY, data text);

2. Run a SELECT statement:

SELECT * FROM example_table;

For Timescale Cloud

Check your PostgreSQL logs to see the auditing information recorded by pgaudit. In Timescale Cloud, it’s as easy as navigating to the Logs tab within your service.

Once you have selected the Timescale service you want to inspect the logs, click the Logs tab for the service.

image

And here are your logs.

image

For a local installation (PostgreSQL or self-hosted TimescaleDB)

You can locate your log directory using the following:

SHOW log_directory;

If it’s a relative path, it’ll be relative to the root path for the data directory that you identified earlier.

On many systems, particularly Linux distributions, PostgreSQL logs are often stored in:

/var/log/postgresql/

That's it! It took quite a few steps, but now you have successfully installed and configured pgaudit in your PostgreSQL database.

A Better Foundation for Database Audit Logging 

Implementing audit logging with pgAudit is a significant step towards enhancing your database security and compliance posture.

If you want a high-performance but sturdy database as the foundation for your audit logging (delivered as a service), you can try Timescale Cloud for free for 30 days.

It combines all of your PostgreSQL faves—a wide ecosystem of tools and connectors, full SQL support, and battle-tested reliability—with a hard-working feature set that takes PostgreSQL to the next level for time series, events, analytics, and even AI. And with the pgAudit extension (among many others) available by default, it’s production-ready for even your most sensitive datasets.

On this page

    Try for free

    Start supercharging your PostgreSQL today.