---
title: Audit Logging - Done
slug: audit-logging-done
createdAt: 2025-01-06T23:23:03.957Z
---

# Audit Logging

## Function

logAuditEvent(userId, workspaceId, action, type, object, detail, datetimeUTC)

## Description

The logAuditEvent function captures essential audit information every time a user performs an action within your application. It gathers user identifiers, action details, timestamp, IP address, geolocation, and device information, then compiles all data into a structured JSON object suitable for logging.

## Input Parameters

| Parameter   | Type   | Description                                                                                                                                                               |
| ----------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| userId      | String | The unique identifier of the user performing the action.                                                                                                                  |
| workspaceId | String | The unique identifier of the workspace or project where the action is performed.                                                                                          |
| action      | String | The type of action performed - e.g. `Login` `Logout` `Create` `Edit` `Delete` `Download`                                                                                  |
| type        | String | The category or type of object affected - `Document` `User` `Expert` `Setting` `Data`                                                                                     |
| object      | String | A name for the type of object selected. These should be short and standardized. For example on EveryAnswer we may use this to be the name of the Expert that is modified. |
| detail      | String | Additional long details or context about the action performed.                                                                                                            |
| datetime    | Date   | UTC Date/Time of Event                                                                                                                                                    |

## Script

```javascript
/**
 * Logs an audit event with comprehensive user, device, and location information.
 *
 * @param {string} userId - The unique identifier of the user performing the action.
 * @param {string} workspaceId - The unique identifier of the workspace or project.
 * @param {string} action - A descriptive string detailing the action performed.
 * @param {string} type - The category or type of action (e.g., 'CREATE', 'UPDATE', 'DELETE').
 * @param {string} object - The target object of the action (e.g., 'Document', 'User').
 *
 * @returns {Promise<void>} - A promise that resolves when the audit log is processed.
 */
async function logAuditEvent(userId, workspaceId, action, type, object) {
  // 1. Collect the current date and time in UTC
  const timestamp = new Date().toISOString();

  // 2. Initialize variables for IP and location
  let ip = 'Unavailable';
  let location = 'Unavailable';

  try {
    // 2.a. Fetch the user's IP address using a third-party API
    const ipResponse = await fetch('https://api.ipify.org?format=json');
    if (ipResponse.ok) {
      const ipData = await ipResponse.json();
      ip = ipData.ip;

      // 2.b. Fetch geolocation data based on the IP address
      const geoResponse = await fetch(`https://ipapi.co/${ip}/json/`);
      if (geoResponse.ok) {
        const geoData = await geoResponse.json();
        location = `${geoData.city}, ${geoData.region}, ${geoData.country_name}`;
      } else {
        console.warn('Failed to fetch geolocation data.');
      }
    } else {
      console.warn('Failed to fetch IP address.');
    }
  } catch (error) {
    console.error('Error fetching IP or geolocation:', error);
  }

  // 3. Collect device information from the browser
  const deviceInfo = {
    userAgent: navigator.userAgent,
    platform: navigator.platform,
    screenResolution: `${window.screen.width}x${window.screen.height}`,
    language: navigator.language
  };

  // 4. Assemble the audit log object
  const auditLog = {
    userId,
    workspaceId,
    action,
    type,
    object,
    timestamp,
    ip,
    location,
    deviceInfo
  };

  // 5. Convert the audit log object to JSON
  const auditLogJSON = JSON.stringify(auditLog);

  // 6. TODO: Integrate with our audit logging system
  // Example:
  /*
  try {
    const response = await fetch('https://your-backend-api.com/audit-log', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: auditLogJSON
    });

    if (!response.ok) {
      console.error('Failed to send audit log:', response.statusText);
    }
  } catch (error) {
    console.error('Error sending audit log:', error);
  }
  */

  // 7. For demonstration purposes, log the audit data to the console - remove from Prod version
  console.log('Audit Log:', auditLogJSON);
}
```

## Notes

Gathers details about the user’s device and browser environment, including:

- userAgent: Information about the browser and operating system.
- platform: The platform on which the browser is running (e.g., Win32, MacIntel).
- screenResolution: The screen’s width and height in pixels.
- language: The preferred language setting of the browser.

## Dependencies

- Retrieves the user’s public IP address by making a request to the ipify API.
- Uses the obtained IP address to fetch geolocation data (city, region, country) from the ipapi.co API.

