gitlab-org--gitlab-foss/app/services/audit_event_service.rb
Stan Hu 143d0e2666 Add support for JSON logging for audit events
This will add audit_json.log that writes one line per audit event. For
example:

{
       "severity":"INFO",
       "time":"2018-10-17T17:38:22.523Z",
       "author_id":3,
       "entity_id":2,
       "entity_type":"Project",
       "change":"visibility",
       "from":"Private",
       "to":"Public",
       "author_name":"John Doe4",
       "target_id":2,
       "target_type":"Project",
       "target_details":"namespace2/project2"
}
2018-10-18 15:59:12 -07:00

45 lines
868 B
Ruby

# frozen_string_literal: true
class AuditEventService
def initialize(author, entity, details = {})
@author, @entity, @details = author, entity, details
end
def for_authentication
@details = {
with: @details[:with],
target_id: @author.id,
target_type: 'User',
target_details: @author.name
}
self
end
def security_event
log_security_event_to_file
log_security_event_to_database
end
private
def base_payload
{
author_id: @author.id,
entity_id: @entity.id,
entity_type: @entity.class.name
}
end
def file_logger
@file_logger ||= Gitlab::AuditJsonLogger.build
end
def log_security_event_to_file
file_logger.info(base_payload.merge(@details))
end
def log_security_event_to_database
SecurityEvent.create(base_payload.merge(details: @details))
end
end