Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Audit Logging Implementation

Audit Logging Implementation

Implement comprehensive audit logging in Google Antigravity for compliance and security tracking.

auditloggingcompliancesecurity
by antigravity-team
⭐0Stars
.antigravity
# Audit Logging for Google Antigravity

Implement comprehensive audit logging for compliance, security, and debugging.

## Database Schema

```sql
CREATE TABLE public.audit_logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID REFERENCES auth.users(id) ON DELETE SET NULL,
    action TEXT NOT NULL,
    entity_type TEXT NOT NULL,
    entity_id TEXT,
    old_values JSONB,
    new_values JSONB,
    metadata JSONB DEFAULT '{}'::jsonb,
    ip_address INET,
    user_agent TEXT,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX idx_audit_user ON public.audit_logs(user_id, created_at DESC);
CREATE INDEX idx_audit_entity ON public.audit_logs(entity_type, entity_id);
CREATE INDEX idx_audit_action ON public.audit_logs(action, created_at DESC);
CREATE INDEX idx_audit_time ON public.audit_logs(created_at DESC);

-- Partition by month for large-scale deployments
-- CREATE TABLE audit_logs_2024_01 PARTITION OF audit_logs FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');
```

## Audit Logger Service

```typescript
// lib/audit.ts
import { createClient } from "@/lib/supabase/server";

export type AuditAction = "create" | "update" | "delete" | "view" | "login" | "logout" | "export" | "import" | "share" | "permission_change";

interface AuditLogParams {
    userId?: string;
    action: AuditAction;
    entityType: string;
    entityId?: string;
    oldValues?: Record<string, unknown>;
    newValues?: Record<string, unknown>;
    metadata?: Record<string, unknown>;
    ipAddress?: string;
    userAgent?: string;
}

export async function createAuditLog(params: AuditLogParams): Promise<void> {
    const supabase = createClient();
    await supabase.from("audit_logs").insert({
        user_id: params.userId,
        action: params.action,
        entity_type: params.entityType,
        entity_id: params.entityId,
        old_values: params.oldValues,
        new_values: params.newValues,
        metadata: params.metadata,
        ip_address: params.ipAddress,
        user_agent: params.userAgent,
    });
}

export function diffObjects(oldObj: Record<string, unknown>, newObj: Record<string, unknown>): { old: Record<string, unknown>; new: Record<string, unknown> } {
    const changes = { old: {} as Record<string, unknown>, new: {} as Record<string, unknown> };
    const allKeys = new Set([...Object.keys(oldObj), ...Object.keys(newObj)]);
    
    for (const key of allKeys) {
        if (JSON.stringify(oldObj[key]) !== JSON.stringify(newObj[key])) {
            changes.old[key] = oldObj[key];
            changes.new[key] = newObj[key];
        }
    }
    return changes;
}
```

## Audit Middleware

```typescript
// lib/audit-middleware.ts
import { NextRequest } from "next/server";
import { createAuditLog, AuditAction } from "./audit";

export function withAudit(action: AuditAction, entityType: string) {
    return async function auditMiddleware(request: NextRequest, handler: () => Promise<Response>, entityId?: string) {
        const userId = request.headers.get("x-user-id") || undefined;
        const ipAddress = request.ip;
        const userAgent = request.headers.get("user-agent") || undefined;

        const response = await handler();

        if (response.ok) {
            await createAuditLog({ userId, action, entityType, entityId, ipAddress, userAgent });
        }

        return response;
    };
}
```

## Database Trigger for Automatic Logging

```sql
CREATE OR REPLACE FUNCTION audit_trigger_function()
RETURNS TRIGGER AS $$
BEGIN
    IF TG_OP = 'INSERT' THEN
        INSERT INTO audit_logs (user_id, action, entity_type, entity_id, new_values)
        VALUES (auth.uid(), 'create', TG_TABLE_NAME, NEW.id::text, to_jsonb(NEW));
    ELSIF TG_OP = 'UPDATE' THEN
        INSERT INTO audit_logs (user_id, action, entity_type, entity_id, old_values, new_values)
        VALUES (auth.uid(), 'update', TG_TABLE_NAME, NEW.id::text, to_jsonb(OLD), to_jsonb(NEW));
    ELSIF TG_OP = 'DELETE' THEN
        INSERT INTO audit_logs (user_id, action, entity_type, entity_id, old_values)
        VALUES (auth.uid(), 'delete', TG_TABLE_NAME, OLD.id::text, to_jsonb(OLD));
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Apply to tables
CREATE TRIGGER audit_posts AFTER INSERT OR UPDATE OR DELETE ON posts FOR EACH ROW EXECUTE FUNCTION audit_trigger_function();
```

## Audit Log Viewer

```typescript
// app/admin/audit/page.tsx
import { createClient } from "@/lib/supabase/server";

export default async function AuditLogPage({ searchParams }: { searchParams: { user?: string; action?: string; entity?: string } }) {
    const supabase = createClient();
    let query = supabase.from("audit_logs").select("*, user:profiles(full_name, email)").order("created_at", { ascending: false }).limit(100);

    if (searchParams.user) query = query.eq("user_id", searchParams.user);
    if (searchParams.action) query = query.eq("action", searchParams.action);
    if (searchParams.entity) query = query.eq("entity_type", searchParams.entity);

    const { data: logs } = await query;

    return (
        <div className="audit-logs">
            <h1>Audit Logs</h1>
            <table>
                <thead>
                    <tr><th>Time</th><th>User</th><th>Action</th><th>Entity</th><th>Details</th></tr>
                </thead>
                <tbody>
                    {logs?.map((log) => (
                        <tr key={log.id}>
                            <td>{new Date(log.created_at).toLocaleString()}</td>
                            <td>{log.user?.full_name || "System"}</td>
                            <td><span className={`badge ${log.action}`}>{log.action}</span></td>
                            <td>{log.entity_type} {log.entity_id}</td>
                            <td><code>{JSON.stringify(log.new_values || log.old_values, null, 2)}</code></td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
}
```

## Export Audit Logs

```typescript
// app/api/admin/audit/export/route.ts
import { NextRequest, NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { createAuditLog } from "@/lib/audit";

export async function GET(request: NextRequest) {
    const supabase = createClient();
    const { data: { user } } = await supabase.auth.getUser();
    
    const startDate = request.nextUrl.searchParams.get("start");
    const endDate = request.nextUrl.searchParams.get("end");

    let query = supabase.from("audit_logs").select("*");
    if (startDate) query = query.gte("created_at", startDate);
    if (endDate) query = query.lte("created_at", endDate);

    const { data: logs } = await query.order("created_at", { ascending: false });

    // Log the export action
    await createAuditLog({ userId: user?.id, action: "export", entityType: "audit_logs", metadata: { startDate, endDate, count: logs?.length } });

    const csv = convertToCSV(logs || []);
    return new NextResponse(csv, { headers: { "Content-Type": "text/csv", "Content-Disposition": "attachment; filename=audit-logs.csv" } });
}

function convertToCSV(data: any[]): string {
    if (!data.length) return "";
    const headers = Object.keys(data[0]).join(",");
    const rows = data.map((row) => Object.values(row).map((v) => JSON.stringify(v)).join(","));
    return [headers, ...rows].join("\n");
}
```

## Best Practices

1. **Immutability**: Never update or delete audit logs
2. **Retention**: Set appropriate retention policies
3. **Sensitive Data**: Redact sensitive information
4. **Indexing**: Index frequently queried columns
5. **Partitioning**: Partition large tables by date

When to Use This Prompt

This audit prompt is ideal for developers working on:

  • audit applications requiring modern best practices and optimal performance
  • Projects that need production-ready audit code with proper error handling
  • Teams looking to standardize their audit development workflow
  • Developers wanting to learn industry-standard audit patterns and techniques

By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their audit implementations.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the audit code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this audit prompt commercially?

Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.

Which AI assistants work best with this prompt?

This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.

How do I customize this prompt for my specific needs?

You can modify the prompt by adding specific requirements, constraints, or preferences. For audit projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...