Audit.MongoClient

April 9, 2025 ยท View on GitHub

MongoDB client audit extension for Audit.NET library.

Generate Audit Logs by adding a Command Event Subscriber into the configuration of the MongoDB Driver.

Audit.MongoClient provides the infrastructure to intercept a MongoClient instance, enabling the generation of audit logs for operations executed within MongoDB.

Note: This library is designed to generate audit events, not for storing events, If you're aiming to store audit events in a Mongo DB collection, you may use the Audit.NET.MongoDB package.

Install

NuGet Package

To install the package run the following command on the Package Manager Console:

PM> Install-Package Audit.MongoClient

NuGet Status NuGet Count

Usage

To enable the audit log for a MongoClient instance you have to register a MongoAuditEventSubscriber instance to the ClusterBuilder.

This registration can be done in several ways:

  • Registering an instance of the provided MongoAuditEventSubscriber:
using Audit.MongoClient;
//...

var mongoSettings = new MongoClientSettings()
{
    Server = new MongoServerAddress("localhost", 27017),
    
    // Register the audit subscriber:
    ClusterConfigurator = clusterBuilder => clusterBuilder.Subscribe(new MongoAuditEventSubscriber()
    {
        IncludeReply = true
    })  
};

// Create the audited client
_client = new MongoDB.Driver.MongoClient(mongoSettings);
  • Calling the provided AddAuditSubscriber() extension method in ClusterBuilder:
using Audit.MongoClient;
//...

var mongoSettings = new MongoClientSettings()
{
    Server = new MongoServerAddress("localhost", 27017),
    ClusterConfigurator = clusterBuilder => clusterBuilder.AddAuditSubscriber(auditConfig => auditConfig
        .IncludeReply())
};

_client = new MongoDB.Driver.MongoClient(mongoSettings);
  • Reusing an existing MongoClientSettings instance by calling the provided AddAuditSubscriber() extension method:
_client = new MongoDB.Driver.MongoClient(mongoSettings.AddAuditSubscriber(cfg => cfg
    .IncludeReply());

Configuration

Output

The audit events are stored using a Data Provider. You can use one of the available data providers or implement your own. Please refer to the data providers section on Audit.NET documentation.

Settings

The MongoAuditEventSubscriber class allows to configure the following settings:

  • EventType: A string that identifies the event type. Default is "{command}". It can contain the following placeholders:
    • {command}: Replaced by the Command Name (insert, update, delete, find, ...)
  • IncludeReply: Specifies whether the command audit event should include the server reply. The reply is not included by default.
  • CommandFilter: Set a filter function to determine which command events to log depending on the command start information. By default all commands are logged.
  • CreationPolicy: Allows to set a specific event creation policy. By default the globally configured creation policy is used. See Audit.NET Event Creation Policy section for more information.
  • AuditDataProvider: Allows to set a specific audit data provider. By default the globally configured data provider is used. See Audit.NET Data Providers section for more information.
  • AuditScopeFactory: Allows to set a specific audit scope factory. By default the globally configured AuditScopeFactory is used.

You can customize these settings using the fluent API provided. Additionally, some settings can be set as functions of the executed command, allowing you to adapt the behavior based on the specific command, such as including the reply only in specific cases.

For example, to only audit insert and delete commands, and include the reply only if its length is less than 512 bytes:

var mongoSettings = new MongoClientSettings()
{
    Server = new MongoServerAddress("localhost", 27017),
    ClusterConfigurator = cc => cc
        .AddAuditSubscriber(auditConfig => auditConfig
            .IncludeReply(cmd => cmd.Reply.ToBson().Length < 512)
            .CommandFilter(cmd => cmd.CommandName is "insert" or "delete"))
};

Output Details

The following table describes the Audit.MongoClient output fields:

MongoCommandEvent

Describes a command call event

Field NameTypeDescription
RequestIdintThe unique request identifier
ConnectionMongoConnectionConnection information
OperationIdlong?The operation identifier
CommandNamestringThe Mongo command name (insert, update, delete, ...)
BodyobjectThe command body
DurationintThe duration of the Mongo Event in milliseconds
Successbool?Indicates if the command succeeded
ReplyobjectThe database reply (optional)
ErrorstringThe database error message if an error occurred, otherwise NULL
TimestampDateTimeThe command event Timestamp

MongoConnection

Contains the command's connection information

Field NameTypeDescription
ClusterIdintThe Connection cluster identifier
EndpointstringThe Connection endpoint
LocalConnectionIdlongThe local connection identifier
ServerConnectionIdlong?The server connection identifier

Output Sample

Mongo insert command:

{
	"Command": {
		"RequestId": 5,
		"Connection": {
			"ClusterId": 1,
			"Endpoint": "Unspecified/localhost:27017",
			"LocalConnectionId": 3,
			"ServerConnectionId": 55
		},
		"OperationId": 1,
		"CommandName": "insert",
		"Body": {
			"insert": "MongoClient",
			"ordered": true,
			"$db": "AuditTest",
			"lsid": {
				"id": "9498dc51-935d-4e3d-9fc0-0031d993059d"
			},
			"documents": [
				{
					"_id": "6574dcbbda3ab8f0437d1c75",
					"test": "this is a test document"
				}
			]
		},
		"Duration": 4,
		"Success": true,
		"Reply": {
			"n": 1,
			"ok": 1.0
		},
		"Timestamp": "2023-12-09T21:31:40.1286166Z"
	},
	"EventType": "3c18aa76-91cb-4c89-b575-342c9158cb44",
	"Environment": {
		"UserName": "Federico Colombo",
		"MachineName": "DESKTOP-ILAR98A",
		"DomainName": "DESKTOP-ILAR98A",
		"CallingMethodName": "Audit.MongoClient.MongoAuditEventSubscriber.Handle()",
		"AssemblyName": "Audit.MongoClient, Version=22.0.2.0, Culture=neutral, PublicKeyToken=null",
		"Culture": "en-US"
	},
	"StartDate": "2023-12-09T21:31:40.1210357Z",
	"EndDate": "2023-12-09T21:31:40.1370355Z",
	"Duration": 16
}

ZZZ Projects - Sponsorship

Entity Framework Extensions and Dapper Plus are major sponsors and are proud to contribute to the development of Audit.NET

Combine the power of auditing with the speed of Bulk Operations to get the best of both worlds โ€” audit and performance.

Entity Framework Extensions - Sponsor

Dapper Plus - Sponsor