Store Audit.NET Trail Logs into a PostgreSQL database
$ dotnet add package Audit.NET.PostgreSqlPostgreSQL Server provider for Audit.NET library (An extensible framework to audit executing operations in .NET).
Store the audit events in a PostgreSQL Table, in JSON format.
NuGet Package To install the package run the following command on the Package Manager Console:
PM> Install-Package Audit.NET.PostgreSql
Please see the Audit.NET Readme
Set the static Audit.Core.Configuration.DataProvider property to set the PostgreSQL data provider, or call the UsePostgreSql method on the fluent configuration. This should be done before any AuditScope creation, i.e. during application startup.
For example:
Audit.Core.Configuration.DataProvider = new PostgreSqlDataProvider()
{
ConnectionString = "Server=127.0.0.1;Port=5432;User Id=admin;Password=admin;Database=postgres;",
TableName = "event",
IdColumnName = "id",
DataColumnName = "data",
DataType = "JSONB",
LastUpdatedDateColumnName = "updated_date",
CustomColumns = new List<CustomColumn>()
{
new CustomColumn("event_type", ev => ev.EventType),
new CustomColumn("user", ev => ev.Environment.UserName),
}
};
Or by using the fluent configuration API:
Audit.Core.Configuration.Setup()
.UsePostgreSql(config => config
.ConnectionString("Server=127.0.0.1;Port=5432;User Id=admin;Password=admin;Database=postgres;")
.TableName("event")
.IdColumnName("id")
.DataColumn("data", DataType.JSONB)
.LastUpdatedColumnName("updated_date")
.CustomColumn("event_type", ev => ev.EventType)
.CustomColumn("user", ev => ev.Environment.UserName));
Mandatory:
Server=127.0.0.1;Port=5432;User Id=postgres;Password=admin;Database=postgres;event.data.id.Optional:
STRING.For example:
CREATE TABLE public.event
(
id bigserial NOT NULL,
inserted_date timestamp without time zone NOT NULL DEFAULT now(),
updated_date timestamp without time zone NOT NULL DEFAULT now(),
data jsonb NOT NULL,
event_type varchar(50),
user varchar(50) NULL,
CONSTRAINT event_pkey PRIMARY KEY (id)
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
This provider implements GetEvent and GetEventAsync methods to obtain an audit event by id:
var event = dataProvider.GetEvent(1000);
The Postgre SQL data provider also includes basic support for querying the events collection.
Use the EnumerateEvents() method on PostgreSqlDataProvider class to run SQL-like queries against the audit events. The EnumerateEvents() method accepts any valid Postgre WHERE clause as a parameter.
For example:
IEnumerable<AuditEvent> events = postgreDataProvider.EnumerateEvents(
"data #> '{Environment,UserName}' = '\"John\"'");
Will return the events whose property Environment.UserName is equal to 'John'.
This post contains information about the query syntax supported by JSONP data type. And here is the PostgreSQL documentation about JSON operators.
For complex querying capabilities, you should use the npgsql driver or the Npgsql EntityFramework provider directly.