Choosing the Right Audit Trail Approach in Ruby

https://blog.bemi.io/audit-trail-in-ruby/
Choosing the Right Audit Trail Approach in Ruby

Ruby gems such as PaperTrail and Audited have been downloaded over a hundred million times and are becoming table stakes in many applications. The Ruby ecosystem offers a wide range of useful tools for building an audit trail, each with its respective pros and cons.

What is an audit trail?

An audit trail (audit log) is a chronological set of records representing documentary evidence of system activities. There are many use cases and benefits to having an audit trail, here are some examples:

  • Disaster recovery: selectively find and restore historical records
  • Customer observability: save time tracking customer activity
  • Regulatory compliance: track data access and simplify audits
  • Fraud detection: identify fraudulent or malicious user activity
  • Enterprise table stakes: allow monitoring activity in an organization
  • Engineering on-call: quickly understand reasons behind data changes

Ruby audit trail solutions

Let’s explore and compare the following approaches to building an audit trail and decide which one of these to choose:

  • Callback-based solutions: PaperTrail, Audited, Mongoid History
  • Trigger-based solutions: Logidze
  • Replication log-based solutions: Bemi Rails
  • Manual tracking: PublicActivity, Ahoy
  • Console command logging: Console1984, Audits1984
  • Custom logging: Marginalia

Callback-Based Solutions

PaperTrail and Audited are very popular gems that integrate with the ActiveRecord object-relational mapper (ORM) by using model callbacks to allow auditing data changes.

When a record is created, updated, or deleted, they insert an additional record that stores changes in a single audit table. This table stores the before/after state in JSON or JSONB formats and a reference pointing to the original record.

This approach is implemented purely on the application level and can be easily enabled for any ActiveRecord-supported database such as PostgreSQL, MySQL, or SQLite.

class MyModel < ApplicationRecord
  has_paper_trail
end

For MongoDB, Mongoid History gem works similarly and integrates with Mongoid, the officially supported object-document mapper (ODM).

They also allow passing and storing application-specific context with changes, such as a user who performed the changes or an API request where the changes were triggered:

# User
Audited.audit_class.as_user(current_user) do
  # Additional context
  audit_comment = { endpoint: "#{request.method} #{request.path}" }.to_json
  my_record.update!(published: true, audit_comment: audit_comment)
end

Pros

  • Easy to get started. An audit trail can be enabled by installing a gem and configuring it with a few lines of code.
  • Customization. It’s possible, for example, to use custom serializers for the before/after state or add a complex condition for disabling tracking.

Cons

  • Reliability and accuracy. Many ActiveRecord methods such as delete, update_column, update_all, delete_all, and so on don’t trigger callbacks. Thus, changes produced by these methods can’t be tracked. Additionally, inserting data changes does not always happen atomically, which may lead to data loss and inconsistency if, for example, there is a network issue.
  • Performance. The database workload increases by roughly 2x because each single record change produces an additional database query that inserts an audit record. This affects the application and database performance.
  • Scalability. A single audit table can get very large. I’ve seen cases where such tables ran out of integers used for primary keys. A large table makes it harder to manage and query at scale while also significantly increasing database resource usage and costs.

Trigger-Based Solutions

Logidze leverages the PostgreSQL triggers functionality and creates a new log_data JSONB column in each auditable table.

When a record is created or updated, PostgreSQL executes a row-based trigger which takes the current values of the record and appends them in the log_data column in a separate SQL query within the same transaction behind the scenes. Here is an example of the log_data:

{
  "v": 2, // current record version,
  "h": [  // list of changes
    {
      "v": 1,                          // change version
      "ts": 1460805759352,             // change timestamp
      "c": { "published": false }      // new values
      "m": {
        "_r": 42,                      // User ID
        "endpoint": "POST /my_records" // Additional context
      }
    },
    ...
  ]
}

It also allows passing and storing application-specific context with ActiveRecord changes, for example:

# User ID
Logidze.with_responsible(current_user.id) do
  my_record.update!(published: true)
end
# Additional context
Logidze.with_meta({ endpoint: "#{request.method} #{request.path}" }) do
  my_record.update!(published: true)
end

Pros

  • Improved performance. It can be almost 100% faster than callback-based solutions for record inserts and about 10% faster for updates. It still makes additional database queries on each record change, but they’re triggered on the database level skipping ActiveRecord.

Cons

  • No delete tracking. Because audit logs are attached and stored with an original record, deleting the record will lead to losing its entire change history. To overcome this limitation, you can use callback-based solutions designed for marking records as soft-deleted and ignoring them when querying, such as Paranoia, Discard, or ActsAsParanoid. But if you decide to use them, be careful and make sure to read our blog post about their danger and how they can lead to critical incidents.
  • Data structure. The data structure can be hard to work with and query directly. The field names in JSON are shortened to 1-2 characters to save disk space but this worsens the readability. Selecting records with the included JSON can significantly decrease database query performance because of PostgreSQL TOAST, so be careful with SELECT * ... SQL statements. It’s also difficult to construct, for example, a timeline of all changes across multiple records without knowing and fetching them in advance.
  • Complexity. Understanding and changing the code for complex triggers with hundreds of lines in SQL can be challenging. Just a single mistake in an SQL function can break all queries. The context passing can also be tricky. For example, if you use PostgreSQL with a connection pooler such as PgBouncer, you need to wrap your queries into a transaction because Logidze relies on PostgreSQL local parameters. But at the same time, if you use transactions, it’s impossible to pass application context to changes that are triggered after “commit” Rails callbacks.

Replication Log-Based Solutions

Bemi Rails uses the native PostgreSQL replication log called Write-Ahead Log (WAL) which records all changes before they are flushed on a disk. 

Traditionally, the PostgreSQL WAL is used for data recovery after a database crash by replaying records or replicating changes to standby read replicas. Bemi uses the same functionality:

  • Bemi Core connects to the PostgreSQL WAL like a standby replica. It ingests and logically decodes all changes asynchronously and then stores them with the before/after states.
  • Bemi Rails allows setting the application context and passing it directly to the WAL with data changes without the need to update the database structure.
# Custom context
Bemi.set_context(
  user_id: current_user.id,
  endpoint: "#{request.method} #{request.path}",
)
# Data change that will be passed with the context into the PostgreSQL WAL
my_record.update!(published: true)

Pros

  • Reliability and accuracy. The PostgreSQL WAL is the source of truth for all data changes. Data changes will be captured even when they are produced by executing a direct SQL query within or outside the application.
  • Performance. Audit logs are ingested asynchronously without affecting runtime performance. The application context is passed to the WAL directly from the application, but it has a minimal performance impact since it doesn’t get stored and processed as regular PostgreSQL data.

Cons

  • Infrastructure complexity. Ingesting logically decoded changes requires running a separate worker process that connects to the database’s replication log. This can be similar to or even more challenging than trying to run a self-managed database replica instance in a cluster. For example, this solution requires creating a replication slot and maintaining the ingested position in the WAL, implementing heartbeats, ingesting and serializing logically decoded WAL records, stitching them with application context, etc.
  • Scalability. Similarly to the callback-based solutions, all audit records are stored in a single table. At scale, this table can become difficult to query and costly to manage.

Full disclosure: I’m one of the Bemi core contributors. Check out our Bemi.io cloud platform if you want to enable an automatic audit trail without the need to manage the infrastructure and deal with scalability issues yourself.

Manual Tracking

PublicActivity is a gem similar to callback-based solutions that track data changes. Its main difference is that it also allows creating custom activity events for database records that can be serialized and translated with Rails i18n.

my_record.create_activity(
  key: 'my_model.commented_on',
  owner: current_user
)

Ahoy allows tracking and collecting analytics data in a Ruby on Rails application. It is similar to, for example, automatic page visit tracking in Google Analytics. But it can also record custom events in controllers.

def update
  ahoy.track('Updated', endpoint: "#{request.method} #{request.path}")
  MyModel.find(params[:id]).update!(published: true)
end

Pros

  • Versatility. Creating custom audit trail records manually can be useful when it is necessary to record activities that didn’t change data or didn’t map 1-to-1 to records’ data changes.

Cons

  • Cumbersomeness. These solutions require manually triggering all actions that need to be recorded and updating the codebase in many places. This can be time-consuming and can increase code complexity. It is also easy to forget to trigger the right action, which may lead to an incomplete audit log.
  • Flexibility. While these solutions give some manual control, they are limited either to controller actions or ActiveRecord models. This may not be flexible enough to record all system activities. For example, recording that a background processing job made changes via an API request in an external system, such as a payment processing service.

Console Command Logging

Console1984 forces developers to specify a reason when they load a Rails console and record it with all executed console commands by storing them in a database.

$ rails c
Bob, why are you using this console today?
> Migrating customer data, see ticket #781923
> user = User.find(...)
...

In a Rails console, it breaks down a session into two access modes. One is the regular “protected” mode available after specifying a Rails console access reason. The other one is the “sensitive” mode which requires additional explicit consent when accessing sensitive information, such as executing a method that decrypts sensitive data or making external HTTP requests.

It also comes with the UI after installing the Audits1984 gem. This gem allows reviewing console sessions by approving or flagging them and leaving comments.

Pros

  • Auditable console sessions. Manually executed commands by developers can automatically be logged and reviewed later.

Cons

  • Loose control. In Ruby, it is very easy to modify any class and method definitions dynamically. It means that someone who has access to a Rails console can find workarounds and execute some commands that won’t be logged. To make logging more reliable and improve internal controls, teams may want to disable production console access and build workflows for running only pre-approved scripts.

Custom Logging

Ruby on Rails logging functionality allows logging anything in any text format.

payload = {
  user_id: current_user.id,
  endpoint: "#{request.method} #{request.path}",
}
Rails.logger.info("CUSTOM_LOG_MESSAGE: #{payload.to_json}")

Starting with Ruby on Rails version 7, previously with the Marginalia gem, it is also possible to pass custom application context via ActiveSupport::CurrentAttributes with ActiveRecord logs.

Current.user = current_user.id
Current.endpoint = "#{request.method} #{request.path}"
config.active_record.query_log_tags = [
  {
    user_id: -> { Current.user.id },
    endpoint: -> { Current.endpoint },
  },
]
MyRecord.all
# Account Load (0.3ms)  SELECT `my_records`.* FROM `my_records`
# /*user_id:1,endpoint:POST /my_records*/

Pros

  • Flexibility. These are the most flexible solutions that allow recording activities in custom format in text logs.

Cons

  • Consumption. Collecting unstructured text logs across all application instances and consuming them might be challenging. Depending on the use case, it might be required to clean up the logs, parse them, and save them in some data storage in a more structured format that allows quick lookups with filters. It might also be required to aggregate the logs by a transaction, an API request, etc. For example, if one log entry says that a record was created by a user, there could be another entry that says that this record creation was not committed and was rolled back.

Conclusion

There is a large number of Ruby gems available that can help with building an audit trail. As a rule of thumb, you can choose the right tool or a combination depending on your needs:

  • Basic change tracking: if you need it for troubleshooting purposes, you can use Audited, which also allows automatically deleting all audit records keeping only the last N numbers of changes.
  • Change diffing and rollbacks: for basic change tracking with additional features for querying them, PaperTrail is your best choice.
  • MongoDB and Mongoid: if you use Mongoid object-document mapper, then go with Mongoid History.
  • Performance over deletion tracking and simplicity: if you use PostgreSQL, then you can choose Logidze.
  • Reliability with zero performance overhead: if you use PostgreSQL and need complete change tracking accuracy and reliability without runtime overhead, go with Bemi Rails.
  • Simple activity feed UIs: if you need to build a simple activity feed constructed around your records, then go with PublicActivity, which also supports i18n for multi-language interfaces.
  • HTTP request tracking: if you need to track HTTP requests in a structured format, then Ahoy is your best choice.
  • Console session auditing: if you need to log and audit the commands executed in Rails consoles, go with Console1984 and Audits1984.
  • Troubleshooting recent issues: you can use application logs to troubleshoot issues and use Marginalia to automatically annotate log entries to add more context.

Also check out the new Ruby Rogues podcast episode where we talk about tools, patterns, and techniques for data recovery in more detail.

{
"by": "exAspArk",
"descendants": 7,
"id": 40230354,
"kids": [
40233292,
40233080,
40234662,
40233257,
40233330,
40238324
],
"score": 46,
"time": 1714602262,
"title": "Choosing the Right Audit Trail Approach in Ruby",
"type": "story",
"url": "https://blog.bemi.io/audit-trail-in-ruby/"
}
{
"author": "Evgeny Li",
"date": "2024-07-26T18:52:08.000Z",
"description": "The Ruby ecosystem offers a wide range of tools for building an audit trail, each with its pros and cons. So, which one is the best choice?",
"image": "https://blog.bemi.io/content/images/2024/05/Audit-Trail-1.jpg",
"logo": null,
"publisher": "Bemi Blog",
"title": "Choosing the Right Audit Trail Approach in Ruby",
"url": "https://blog.bemi.io/audit-trail-in-ruby/"
}
{
"url": "https://blog.bemi.io/audit-trail-in-ruby/",
"title": "Choosing the Right Audit Trail Approach in Ruby",
"description": "Ruby gems such as PaperTrail and Audited have been downloaded over a hundred million times and are becoming table stakes in many applications. The Ruby ecosystem offers a wide range of useful tools for...",
"links": [
"https://blog.bemi.io/audit-trail-in-ruby/"
],
"image": "https://blog.bemi.io/content/images/2024/05/Audit-Trail-1.jpg",
"content": "<div>\n<article>\n <figure>\n <img srcset=\"https://blog.bemi.io/content/images/size/w300/2024/05/Audit-Trail-1.jpg 300w, https://blog.bemi.io/content/images/size/w600/2024/05/Audit-Trail-1.jpg 600w, https://blog.bemi.io/content/images/size/w1000/2024/05/Audit-Trail-1.jpg 1000w, https://blog.bemi.io/content/images/size/w2000/2024/05/Audit-Trail-1.jpg 2000w\" src=\"https://blog.bemi.io/content/images/size/w2000/2024/05/Audit-Trail-1.jpg\" alt=\"Choosing the Right Audit Trail Approach in Ruby\" />\n </figure>\n <section>\n <p>Ruby gems such as <a target=\"_blank\" href=\"https://github.com/paper-trail-gem/paper_trail?ref=blog.bemi.io\">PaperTrail</a> and <a target=\"_blank\" href=\"https://github.com/collectiveidea/audited?ref=blog.bemi.io\">Audited</a> have been downloaded over a hundred million times and are becoming table stakes in many applications. The Ruby ecosystem offers a wide range of useful tools for building an audit trail, each with its respective pros and cons.</p><h3 id=\"what-is-an-audit-trail\">What is an audit trail?</h3><p>An audit trail (audit log) is a chronological set of records representing documentary evidence of system activities. There are many use cases and benefits to having an audit trail, here are some examples:</p><ul><li><strong>Disaster recovery</strong>: selectively find and restore historical records</li><li><strong>Customer observability</strong>: save time tracking customer activity</li><li><strong>Regulatory compliance</strong>: track data access and simplify audits</li><li><strong>Fraud detection</strong>: identify fraudulent or malicious user activity</li><li><strong>Enterprise table stakes</strong>: allow monitoring activity in an organization</li><li><strong>Engineering on-call</strong>: quickly understand reasons behind data changes</li></ul><h3 id=\"ruby-audit-trail-solutions\">Ruby audit trail solutions</h3><p>Let’s explore and compare the following approaches to building an audit trail and decide which one of these to choose:</p><ul><li><strong>Callback-based solutions</strong>: PaperTrail, Audited, Mongoid History</li><li><strong>Trigger-based solutions</strong>: Logidze</li><li><strong>Replication log-based solutions</strong>: Bemi Rails</li><li><strong>Manual tracking</strong>: PublicActivity, Ahoy</li><li><strong>Console command logging</strong>: Console1984, Audits1984</li><li><strong>Custom logging</strong>: Marginalia</li></ul><hr /><h2 id=\"callback-based-solutions\">Callback-Based Solutions</h2><figure><img src=\"https://cdn-images-1.medium.com/max/1600/1*uB_AzdPexdjAku29iDXXPQ.png\" /></figure><p><a target=\"_blank\" href=\"https://github.com/paper-trail-gem/paper_trail?ref=blog.bemi.io\"><strong>PaperTrail</strong></a> and<strong> </strong><a target=\"_blank\" href=\"https://github.com/collectiveidea/audited?ref=blog.bemi.io\"><strong>Audited</strong></a> are very popular gems that integrate with the ActiveRecord object-relational mapper (ORM) by using model callbacks to allow auditing data changes.</p><p>When a record is created, updated, or deleted, they insert an additional record that stores changes in a single audit table. This table stores the before/after state in JSON or JSONB formats and a reference pointing to the original record.</p><p>This approach is implemented purely on the application level and can be easily enabled for any ActiveRecord-supported database such as PostgreSQL, MySQL, or SQLite.</p><pre><code>class MyModel &lt; ApplicationRecord\n has_paper_trail\nend</code></pre><p>For MongoDB, <a target=\"_blank\" href=\"https://github.com/mongoid/mongoid-history?ref=blog.bemi.io\"><strong>Mongoid History</strong></a> gem works similarly and integrates with Mongoid, the officially supported object-document mapper (ODM).</p><p>They also allow passing and storing application-specific context with changes, such as a user who performed the changes or an API request where the changes were triggered:</p><pre><code># User\nAudited.audit_class.as_user(current_user) do\n # Additional context\n audit_comment = { endpoint: \"#{request.method} #{request.path}\" }.to_json\n my_record.update!(published: true, audit_comment: audit_comment)\nend</code></pre><h3 id=\"pros\">Pros</h3><ul><li><strong>Easy to get started</strong>. An audit trail can be enabled by installing a gem and configuring it with a few lines of code.</li><li><strong>Customization</strong>. It’s possible, for example, to use custom serializers for the before/after state or add a complex condition for disabling tracking.</li></ul><h3 id=\"cons\">Cons</h3><ul><li><strong>Reliability and accuracy</strong>. Many ActiveRecord methods such as <code>delete</code>, <code>update_column</code>, <code>update_all</code>, <code>delete_all</code>, and so on don’t trigger callbacks. Thus, changes produced by these methods can’t be tracked. Additionally, inserting data changes does not always happen atomically, which may lead to data loss and inconsistency if, for example, there is a network issue.</li><li><strong>Performance</strong>. The database workload increases by roughly 2x because each single record change produces an additional database query that inserts an audit record. This affects the application and database performance.</li><li><strong>Scalability</strong>. A single audit table can get very large. I’ve seen cases where such tables ran out of integers used for primary keys. A large table makes it harder to manage and query at scale while also significantly increasing database resource usage and costs.</li></ul><h2 id=\"trigger-based-solutions\">Trigger-Based Solutions</h2><figure><img src=\"https://cdn-images-1.medium.com/max/1600/1*j5ozkmkbtEpHAh1yt3c0LQ.png\" /></figure><p><a target=\"_blank\" href=\"https://github.com/palkan/logidze?ref=blog.bemi.io\"><strong>Logidze</strong></a> leverages the PostgreSQL triggers functionality and creates a new <code>log_data</code> JSONB column in each auditable table.</p><p>When a record is created or updated, PostgreSQL executes a row-based trigger which takes the current values of the record and appends them in the <code>log_data</code> column in a separate SQL query within the same transaction behind the scenes. Here is an example of the <code>log_data</code>:</p><pre><code>{\n \"v\": 2, // current record version,\n \"h\": [ // list of changes\n {\n \"v\": 1, // change version\n \"ts\": 1460805759352, // change timestamp\n \"c\": { \"published\": false } // new values\n \"m\": {\n \"_r\": 42, // User ID\n \"endpoint\": \"POST /my_records\" // Additional context\n }\n },\n ...\n ]\n}</code></pre><p>It also allows passing and storing application-specific context with ActiveRecord changes, for example:</p><pre><code># User ID\nLogidze.with_responsible(current_user.id) do\n my_record.update!(published: true)\nend\n# Additional context\nLogidze.with_meta({ endpoint: \"#{request.method} #{request.path}\" }) do\n my_record.update!(published: true)\nend</code></pre><h3 id=\"pros-1\">Pros</h3><ul><li><strong>Improved performance</strong>. It can be almost 100% faster than callback-based solutions for record inserts and about 10% faster for updates. It still makes additional database queries on each record change, but they’re triggered on the database level skipping ActiveRecord.</li></ul><h3 id=\"cons-1\">Cons</h3><ul><li><strong>No delete tracking</strong>. Because audit logs are attached and stored with an original record, deleting the record will lead to losing its entire change history. To overcome this limitation, you can use callback-based solutions designed for marking records as soft-deleted and ignoring them when querying, such as <a target=\"_blank\" href=\"https://github.com/rubysherpas/paranoia?ref=blog.bemi.io\">Paranoia</a>, <a target=\"_blank\" href=\"https://github.com/jhawthorn/discard?ref=blog.bemi.io\">Discard</a>, or <a target=\"_blank\" href=\"https://github.com/ActsAsParanoid/acts_as_paranoid?ref=blog.bemi.io\">ActsAsParanoid</a>. But if you decide to use them, be careful and make sure to read our <a target=\"_blank\" href=\"https://blog.bemi.io/soft-deleting-chaos/\">blog post</a> about their danger and how they can lead to critical incidents.</li><li><strong>Data structure</strong>. The data structure can be hard to work with and query directly. The field names in JSON are shortened to 1-2 characters to save disk space but this worsens the readability. Selecting records with the included JSON can significantly decrease database query performance because of <a target=\"_blank\" href=\"https://wiki.postgresql.org/wiki/TOAST?ref=blog.bemi.io\">PostgreSQL TOAST</a>, so be careful with <code>SELECT * ...</code> SQL statements. It’s also difficult to construct, for example, a timeline of all changes across multiple records without knowing and fetching them in advance.</li><li><strong>Complexity</strong>. Understanding and changing the code for complex triggers with hundreds of lines in SQL can be challenging. Just a single mistake in an SQL function can break all queries. The context passing can also be tricky. For example, if you use PostgreSQL with a connection pooler such as PgBouncer, you need to wrap your queries into a transaction because Logidze relies on <a target=\"_blank\" href=\"https://www.postgresql.org/docs/current/sql-set.htm?ref=blog.bemi.io\">PostgreSQL local parameters</a>. But at the same time, if you use transactions, it’s impossible to pass application context to changes that are triggered after “commit” Rails callbacks.</li></ul><h2 id=\"replication-log-based-solutions\">Replication Log-Based Solutions</h2><figure><img src=\"https://cdn-images-1.medium.com/max/1600/1*i3FrMjpJktnx1PoG5vDtYg.png\" /></figure><p><a target=\"_blank\" href=\"https://github.com/BemiHQ/bemi-rails?ref=blog.bemi.io\"><strong>Bemi Rails</strong></a> uses the native PostgreSQL replication log called <a target=\"_blank\" href=\"https://www.postgresql.org/docs/current/wal-intro.html?ref=blog.bemi.io\">Write-Ahead Log (WAL)</a> which records all changes before they are flushed on a disk. </p><p>Traditionally, the PostgreSQL WAL is used for data recovery after a database crash by replaying records or replicating changes to standby read replicas. Bemi uses the same functionality:</p><ul><li><a target=\"_blank\" href=\"https://github.com/BemiHQ/bemi?ref=blog.bemi.io\">Bemi Core</a> connects to the PostgreSQL WAL like a standby replica. It ingests and logically decodes all changes asynchronously and then stores them with the before/after states.</li><li>Bemi Rails allows setting the application context and passing it directly to the WAL with data changes without the need to update the database structure.</li></ul><pre><code># Custom context\nBemi.set_context(\n user_id: current_user.id,\n endpoint: \"#{request.method} #{request.path}\",\n)\n# Data change that will be passed with the context into the PostgreSQL WAL\nmy_record.update!(published: true)</code></pre><h3 id=\"pros-2\">Pros</h3><ul><li><strong>Reliability and accuracy</strong>. The PostgreSQL WAL is the source of truth for all data changes. Data changes will be captured even when they are produced by executing a direct SQL query within or outside the application.</li><li><strong>Performance</strong>. Audit logs are ingested asynchronously without affecting runtime performance. The application context is passed to the WAL directly from the application, but it has a minimal performance impact since it doesn’t get stored and processed as regular PostgreSQL data.</li></ul><h3 id=\"cons-2\">Cons</h3><ul><li><strong>Infrastructure complexity</strong>. Ingesting logically decoded changes requires running a separate worker process that connects to the database’s replication log. This can be similar to or even more challenging than trying to run a self-managed database replica instance in a cluster. For example, this solution requires creating a replication slot and maintaining the ingested position in the WAL, implementing heartbeats, ingesting and serializing logically decoded WAL records, stitching them with application context, etc.</li><li><strong>Scalability</strong>. Similarly to the callback-based solutions, all audit records are stored in a single table. At scale, this table can become difficult to query and costly to manage.</li></ul><p><em>Full disclosure: I’m one of the Bemi core contributors. Check out our </em><a target=\"_blank\" href=\"https://bemi.io/?ref=blog.bemi.io\"><em>Bemi.io</em></a><em> cloud platform if you want to enable an automatic audit trail without the need to manage the infrastructure and deal with scalability issues yourself.</em></p><h2 id=\"manual-tracking\">Manual Tracking</h2><figure><img src=\"https://cdn-images-1.medium.com/max/1600/1*RA3qzROOSLAPkbI9ILxB6g.png\" /></figure><p><a target=\"_blank\" href=\"https://github.com/public-activity/public_activity?ref=blog.bemi.io\"><strong>PublicActivity</strong></a><strong> </strong>is a gem similar to callback-based solutions that track data changes. Its main difference is that it also allows creating custom activity events for database records that can be serialized and translated with <a target=\"_blank\" href=\"https://guides.rubyonrails.org/i18n.html?ref=blog.bemi.io\">Rails i18n</a>.</p><pre><code>my_record.create_activity(\n key: 'my_model.commented_on',\n owner: current_user\n)</code></pre><p><a target=\"_blank\" href=\"https://github.com/ankane/ahoy?ref=blog.bemi.io\"><strong>Ahoy</strong></a> allows tracking and collecting analytics data in a Ruby on Rails application. It is similar to, for example, automatic page visit tracking in Google Analytics. But it can also record custom events in controllers.</p><pre><code>def update\n ahoy.track('Updated', endpoint: \"#{request.method} #{request.path}\")\n MyModel.find(params[:id]).update!(published: true)\nend</code></pre><h3 id=\"pros-3\">Pros</h3><ul><li><strong>Versatility</strong>. Creating custom audit trail records manually can be useful when it is necessary to record activities that didn’t change data or didn’t map 1-to-1 to records’ data changes.</li></ul><h3 id=\"cons-3\">Cons</h3><ul><li><strong>Cumbersomeness</strong>. These solutions require manually triggering all actions that need to be recorded and updating the codebase in many places. This can be time-consuming and can increase code complexity. It is also easy to forget to trigger the right action, which may lead to an incomplete audit log.</li><li><strong>Flexibility</strong>. While these solutions give some manual control, they are limited either to controller actions or ActiveRecord models. This may not be flexible enough to record all system activities. For example, recording that a background processing job made changes via an API request in an external system, such as a payment processing service.</li></ul><h2 id=\"console-command-logging\">Console Command Logging</h2><figure><img src=\"https://cdn-images-1.medium.com/max/1600/1*SSKjFWjna5r30v567xadKA.png\" /></figure><p><a target=\"_blank\" href=\"https://github.com/basecamp/console1984?ref=blog.bemi.io\"><strong>Console1984</strong></a> forces developers to specify a reason when they load a Rails console and record it with all executed console commands by storing them in a database.</p><pre><code>$ rails c\nBob, why are you using this console today?\n&gt; Migrating customer data, see ticket #781923\n&gt; user = User.find(...)\n...</code></pre><p>In a Rails console, it breaks down a session into two access modes. One is the regular “protected” mode available after specifying a Rails console access reason. The other one is the “sensitive” mode which requires additional explicit consent when accessing sensitive information, such as executing a method that decrypts sensitive data or making external HTTP requests.</p><p>It also comes with the UI after installing the <a target=\"_blank\" href=\"https://github.com/basecamp/audits1984?ref=blog.bemi.io\"><strong>Audits1984</strong></a> gem. This gem allows reviewing console sessions by approving or flagging them and leaving comments.</p><h3 id=\"pros-4\">Pros</h3><ul><li><strong>Auditable console sessions</strong>. Manually executed commands by developers can automatically be logged and reviewed later.</li></ul><h3 id=\"cons-4\">Cons</h3><ul><li><strong>Loose control</strong>. In Ruby, it is very easy to modify any class and method definitions dynamically. It means that someone who has access to a Rails console can find workarounds and execute some commands that won’t be logged. To make logging more reliable and improve internal controls, teams may want to disable production console access and build workflows for running only pre-approved scripts.</li></ul><h2 id=\"custom-logging\">Custom Logging</h2><figure><img src=\"https://cdn-images-1.medium.com/max/1600/1*4-0FLfRJN5prxrowiHMnQA.png\" /></figure><p>Ruby on Rails logging functionality allows logging anything in any text format.</p><pre><code>payload = {\n user_id: current_user.id,\n endpoint: \"#{request.method} #{request.path}\",\n}\nRails.logger.info(\"CUSTOM_LOG_MESSAGE: #{payload.to_json}\")</code></pre><p>Starting with Ruby on Rails version 7, previously with the <a target=\"_blank\" href=\"https://github.com/basecamp/marginalia?ref=blog.bemi.io\"><strong>Marginalia</strong></a> gem, it is also possible to pass custom application context via <code>ActiveSupport::CurrentAttributes</code> with ActiveRecord logs.</p><pre><code>Current.user = current_user.id\nCurrent.endpoint = \"#{request.method} #{request.path}\"\nconfig.active_record.query_log_tags = [\n {\n user_id: -&gt; { Current.user.id },\n endpoint: -&gt; { Current.endpoint },\n },\n]\nMyRecord.all\n# Account Load (0.3ms) SELECT `my_records`.* FROM `my_records`\n# /*user_id:1,endpoint:POST /my_records*/\n</code></pre><h3 id=\"pros-5\">Pros</h3><ul><li><strong>Flexibility</strong>. These are the most flexible solutions that allow recording activities in custom format in text logs.</li></ul><h3 id=\"cons-5\">Cons</h3><ul><li><strong>Consumption</strong>. Collecting unstructured text logs across all application instances and consuming them might be challenging. Depending on the use case, it might be required to clean up the logs, parse them, and save them in some data storage in a more structured format that allows quick lookups with filters. It might also be required to aggregate the logs by a transaction, an API request, etc. For example, if one log entry says that a record was created by a user, there could be another entry that says that this record creation was not committed and was rolled back.</li></ul><hr /><h2 id=\"conclusion\">Conclusion</h2><p>There is a large number of Ruby gems available that can help with building an audit trail. As a rule of thumb, you can choose the right tool or a combination depending on your needs:</p><ul><li><strong>Basic change tracking</strong>:<strong> </strong>if you need it for troubleshooting purposes, you can use <a target=\"_blank\" href=\"https://github.com/collectiveidea/audited?ref=blog.bemi.io\">Audited</a>, which also allows automatically deleting all audit records keeping only the last N numbers of changes.</li><li><strong>Change diffing and rollbacks</strong>: for basic change tracking with additional features for querying them, <a target=\"_blank\" href=\"https://github.com/paper-trail-gem/paper_trail?ref=blog.bemi.io\">PaperTrail</a> is your best choice.</li><li><strong>MongoDB and Mongoid</strong>: if you use Mongoid object-document mapper, then go with <a target=\"_blank\" href=\"https://github.com/mongoid/mongoid-history?ref=blog.bemi.io\">Mongoid History</a>.</li><li><strong>Performance over deletion tracking and simplicity</strong>: if you use PostgreSQL, then you can choose <a target=\"_blank\" href=\"https://github.com/palkan/logidze?ref=blog.bemi.io\">Logidze</a>.</li><li><strong>Reliability with zero performance overhead</strong>: if you use PostgreSQL and need complete change tracking accuracy and reliability without runtime overhead, go with <a target=\"_blank\" href=\"https://github.com/BemiHQ/bemi-rails?ref=blog.bemi.io\">Bemi Rails</a>.</li><li><strong>Simple activity feed UIs</strong>: if you need to build a simple activity feed constructed around your records, then go with <a target=\"_blank\" href=\"https://github.com/public-activity/public_activity?ref=blog.bemi.io\">PublicActivity</a>, which also supports i18n for multi-language interfaces.</li><li><strong>HTTP request tracking</strong>: if you need to track HTTP requests in a structured format, then <a target=\"_blank\" href=\"https://github.com/ankane/ahoy?ref=blog.bemi.io\">Ahoy</a> is your best choice.</li><li><strong>Console session auditing</strong>: if you need to log and audit the commands executed in Rails consoles, go with <a target=\"_blank\" href=\"https://github.com/basecamp/console1984?ref=blog.bemi.io\">Console1984</a> and <a target=\"_blank\" href=\"https://github.com/basecamp/audits1984?ref=blog.bemi.io\">Audits1984</a>.</li><li><strong>Troubleshooting recent issues</strong>: you can use application logs to troubleshoot issues and use <a target=\"_blank\" href=\"https://github.com/basecamp/marginalia?ref=blog.bemi.io\">Marginalia</a> to automatically annotate log entries to add more context.</li></ul><hr /><figure><img src=\"https://blog.bemi.io/content/images/2024/07/Untitled.jpg\" srcset=\"https://blog.bemi.io/content/images/size/w600/2024/07/Untitled.jpg 600w, https://blog.bemi.io/content/images/size/w1000/2024/07/Untitled.jpg 1000w, https://blog.bemi.io/content/images/size/w1600/2024/07/Untitled.jpg 1600w, https://blog.bemi.io/content/images/2024/07/Untitled.jpg 2400w\" /></figure><p><em>Also check out the new </em><a target=\"_blank\" href=\"https://topenddevs.com/podcasts/ruby-rogues/episodes/navigating-sql-data-changes-tools-and-techniques-for-data-recovery-ruby-645?ref=blog.bemi.io\"><em>Ruby Rogues podcast episode</em></a><em> where we talk about tools, patterns, and techniques for data recovery in more detail.</em></p>\n </section>\n</article>\n</div>",
"author": "@exAspArk",
"favicon": "https://blog.bemi.io/content/images/size/w256h256/2024/02/logo-round-2.png",
"source": "blog.bemi.io",
"published": "2024-07-26T18:52:08.000Z",
"ttr": 419,
"type": "article"
}