Skip to main content

Overview

The Audit Logging system provides comprehensive tracking of all user actions, system changes, and security events across the P.FLEX platform. Every significant operation is recorded with timestamps, user information, and detailed context for compliance and troubleshooting.

Audit Log Data Model

The AuditLog interface defines the structure of audit records:
id
string
required
Unique identifier for the audit log entry
timestamp
Date
required
Exact date and time of the action (automatically generated)
user
string
required
Name of the user who performed the action
role
string
required
Role of the user at the time of action (e.g., “Supervisor”, “Jefatura”)
module
string
required
System module where action occurred:
  • ADMIN - Administrative operations
  • ACCESO - Authentication/login events
  • OPERACIONES - Operational changes
  • SISTEMA - System-level events
action
string
required
Brief description of the action performed (e.g., “Crear Usuario”, “Inicio de Sesión”)
details
string
required
Detailed description with context and affected entities
ip
string
required
IP address of the user’s device (e.g., “192.168.1.45”)

Audit Service

The AuditService manages all audit logging:
// Source: audit.service.ts:15-29
@Injectable({ providedIn: 'root' })
export class AuditService {
  // Signal para reactividad en la UI
  readonly logs = signal<AuditLog[]>([
    { 
      id: 'log-init',
      timestamp: new Date(Date.now() - 3600000), 
      user: 'Sistema', 
      role: 'System', 
      module: 'SISTEMA', 
      action: 'Inicio de Servicios', 
      details: 'El sistema se ha iniciado correctamente.', 
      ip: 'localhost' 
    }
  ]);
Audit logs use Angular signals for reactive UI updates. New entries appear in real-time without page refresh.

Logging Operations

Create audit entries using the log() method:
// Source: audit.service.ts:31-48
log(user: string, role: string, module: string, action: string, details: string = '') {
  const newEntry: AuditLog = {
    id: Math.random().toString(36).substr(2, 9),
    timestamp: new Date(),
    user: user || 'Desconocido',
    role: role || '---',
    module: module.toUpperCase(),
    action: action,
    details: details,
    ip: this.generateRandomIP()
  };

  // Agregar al inicio del array
  this.logs.update(currentLogs => [newEntry, ...currentLogs]);
  
  // Opcional: Aquí se podría llamar a un backend real
  console.log('[AUDIT]', newEntry);
}
Logs are prepended to the array so newest entries appear first. The module name is automatically converted to uppercase.

Tracked Events

User Management Events

All user administration actions are logged:
// Source: admin.service.ts:28
this.audit.log(this.state.userName(), this.state.userRole(), 
  'ADMIN', 'Crear Usuario', 
  `Usuario creado: ${newUser.username} (${newUser.role})`);
Module: ADMINDetails: Username and assigned roleExample: “Usuario creado: jperez (Supervisor)”
// Source: admin.service.ts:33
this.audit.log(this.state.userName(), this.state.userRole(), 
  'ADMIN', 'Editar Usuario', 
  `Usuario modificado: ${updatedUser.username}`);
Module: ADMINDetails: Username of modified account
// Source: admin.service.ts:39
this.audit.log(this.state.userName(), this.state.userRole(), 
  'ADMIN', 'Eliminar Usuario', 
  `Usuario eliminado: ${user?.username || id}`);
Module: ADMINDetails: Username or ID of deleted account

Role Management Events

// Source: admin.service.ts:48
this.audit.log(this.state.userName(), this.state.userRole(), 
  'ADMIN', 'Actualizar Rol', 
  `Rol modificado: ${updatedRole.name}`);
Module: ADMINDetails: Role nameTracks: Permission changes and role modifications
// Source: admin.service.ts:54
this.audit.log(this.state.userName(), this.state.userRole(), 
  'ADMIN', 'Eliminar Rol', 
  `Rol eliminado: ${role?.name || id}`);
Module: ADMINDetails: Role name or ID

Machine Management Events

// Source: admin.service.ts:72
this.audit.log(this.state.userName(), this.state.userRole(), 
  'ADMIN', 'Crear Máquina', 
  `Máquina registrada: ${newMachine.name}`);
Module: ADMINDetails: Machine name
// Source: admin.service.ts:77
this.audit.log(this.state.userName(), this.state.userRole(), 
  'ADMIN', 'Actualizar Máquina', 
  `Máquina actualizada: ${updatedMachine.name} - Estado: ${updatedMachine.status}`);
Module: ADMINDetails: Machine name and new status
// Source: admin.service.ts:83
this.audit.log(this.state.userName(), this.state.userRole(), 
  'ADMIN', 'Eliminar Máquina', 
  `Máquina eliminada: ${machine?.name || id}`);
Module: ADMINDetails: Machine name

System Configuration Events

// Source: admin.service.ts:92
this.audit.log(this.state.userName(), this.state.userRole(), 
  'ADMIN', 'Configuración', 
  'Se actualizaron los parámetros globales del sistema.');
Module: ADMIN Action: Configuración Details: Generic message for system-wide configuration changes

Authentication Events

// Source: state.service.ts:142
this.audit.log(name, role, 'ACCESO', 'Inicio de Sesión', 
  `Usuario ${username} inició sesión en ${shift}.`);
Module: ACCESODetails: Username and shift informationExample: “Usuario jperez inició sesión en Turno Día.”
// Source: state.service.ts:149
this.audit.log(user, role, 'ACCESO', 'Cierre de Sesión', 
  'Usuario cerró sesión manualmente.');
Module: ACCESODetails: Logout method (manual vs. automatic timeout)

Operational Events

// Source: state.service.ts:166
this.audit.log(this.userName(), this.userRole(), 'OPERACIONES', 
  'Estado Máquina', 
  `Máquina ${updatedMachine.name} cambió a ${updatedMachine.status}`);
Module: OPERACIONES Action: Estado Máquina Details: Machine name and status change Use case: Track operational changes separate from administrative configuration

Audit Log Display

The audit component presents logs in a comprehensive table:
// Source: audit.component.ts:24-57
<table class="w-full text-sm text-left">
  <thead>
    <tr>
      <th>Fecha / Hora</th>
      <th>Usuario / Rol</th>
      <th>Módulo</th>
      <th>Acción</th>
      <th>IP Origen</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let log of audit.logs()">
      <td>{{ log.timestamp | date:'dd/MM/yyyy HH:mm:ss' }}</td>
      <td>
        <div>{{ log.user }}</div>
        <div class="text-[10px]">{{ log.role }}</div>
      </td>
      <td>
        <span class="badge">{{ log.module }}</span>
      </td>
      <td>
        <div>{{ log.action }}</div>
        <div class="text-xs">{{ log.details }}</div>
      </td>
      <td>{{ log.ip }}</td>
    </tr>
  </tbody>
</table>

Column Breakdown

Fecha / Hora
datetime
Timestamp formatted as DD/MM/YYYY HH:mm:ssExample: 09/03/2026 14:32:15
Usuario / Rol
composite
User’s full name with role displayed belowExample:
Juan Pérez
SUPERVISOR
Módulo
badge
Categorized module with color coding:
  • ADMIN - Blue badge
  • ACCESO - Green badge
  • OPERACIONES - Orange badge
  • SISTEMA - Purple badge
Acción
composite
Action title with detailed description belowExample:
Crear Usuario
Usuario creado: jperez (Supervisor)
IP Origen
string
Source IP address (simulated: 192.168.1.x)
While not shown in the current implementation, audit logs can be filtered by:
  • Date range
  • User name
  • Module type
  • Action type
  • IP address
The current implementation stores logs in memory. For production use, implement persistent storage and retention policies.

Compliance Features

Tamper-Proof

Audit logs cannot be modified or deleted by users (only append operations)

Complete Traceability

Every action includes user identity, timestamp, and detailed context

Real-Time Logging

Events are logged synchronously as they occur

Module Segregation

Actions are categorized by system module for easy filtering

Audit Log Modules

ModulePurposeExample Actions
ADMINAdministrative operationsUser creation, role updates, machine configuration
ACCESOAuthentication eventsLogin, logout, session timeout
OPERACIONESOperational changesMachine status changes, work order updates
SISTEMASystem-level eventsService startup, configuration changes

Best Practices

Audit Logging Guidelines

Log Everything Significant: Track all actions that modify data or affect securityDescriptive Details: Include entity names, old/new values, and relevant contextConsistent Formatting: Use consistent action names across the applicationRegular Review: Monitor audit logs for suspicious activity or policy violationsRetention Policy: Define how long to retain logs based on compliance requirementsExport Capability: Allow exporting logs to CSV/PDF for external auditingAccess Control: Restrict audit log viewing to authorized personnel (Jefatura, Sistemas)

IP Address Tracking

The system simulates IP address tracking:
// Source: audit.service.ts:50-52
private generateRandomIP(): string {
  return `192.168.1.${Math.floor(Math.random() * 254) + 1}`;
}
This is a simulation for demonstration purposes. In production, capture real client IP addresses from HTTP headers.

Integration Points

Audit logging is integrated throughout the application:
// Services that inject AuditService:
- AdminService (src/features/admin/services/admin.service.ts:4)
- StateService (src/services/state.service.ts:29)

// Components that display logs:
- AuditComponent (src/features/audit/audit.component.ts)
- AdminConfigComponent (preview in Security & Logs section)

Future Enhancements

1

Persistent Storage

Store logs in database with proper indexing for fast queries
2

Advanced Filtering

Add date range pickers, multi-select filters, and full-text search
3

Export Functionality

Enable CSV, PDF, and JSON export for compliance reporting
4

Alerting

Configure alerts for suspicious patterns (multiple failed logins, unauthorized access attempts)
5

Data Retention

Implement automatic archival and deletion based on retention policies

Code Reference

Key source files:
  • Audit Service: src/services/audit.service.ts:15-53
  • Audit Interface: src/services/audit.service.ts:4-13
  • Audit Component: src/features/audit/audit.component.ts:6-66
  • Admin Integration: src/features/admin/services/admin.service.ts:4,12
  • Auth Integration: src/services/state.service.ts:29,142,149

Build docs developers (and LLMs) love