Class: JSONLogger

Inherits:
Object
  • Object
show all
Defined in:
lib/ons-json-logger/json_logger.rb

Overview

Class that generates structured JSON log entries.

Instance Method Summary collapse

Constructor Details

#initialize(application:, environment: 'development') ⇒ JSONLogger

Constructor that initialises the JSON logger.

Parameters:

  • application (String)

    the name of the application

  • environment (String) (defaults to: 'development')

    the name of the environment the application is deployed to. Defaults to development

Raises:

  • (ArgumentError)

    if application is nil



13
14
15
16
17
18
# File 'lib/ons-json-logger/json_logger.rb', line 13

def initialize(application:, environment: 'development')
  raise ArgumentError, 'application cannot be nil' if application.nil?

  @application = application
  @environment = environment
end

Instance Method Details

#log(level:, message:, module_name:, user: {}, http: {}, error: {}) ⇒ Object

Returns a structured JSON log entry from the passed arguments.

user optional Hash containing details of the user making the request such as username and IP address http optional Hash containing details of the HTTP request such as the method, path, status code and user agent error optional Hash containing details of an error that occurred such as the error code and message

Parameters:

  • level

    the log level e.g. DEBUG, ERROR, INFO

  • message

    the log message

  • module_name

    the name of the application module/component generating the log message

Raises:

  • (ArgumentError)

    if level is nil

  • (ArgumentError)

    id message is nil

  • (ArgumentError)

    if module_name is nil



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/ons-json-logger/json_logger.rb', line 31

def log(level:, message:, module_name:, user: {}, http: {}, error: {})
  raise ArgumentError, 'level cannot be nil' if level.nil?
  raise ArgumentError, 'message' if level.nil?
  raise ArgumentError, 'module_name cannot be nil' if level.nil?

  log_entry = {
    timestamp: Time.now.utc.iso8601,
    level:,
    message:,
    application: @application,
    environment: @environment,
    module: module_name
  }

  # Add optional fields if they are provided.
  log_entry[:user]  = user unless user.empty?
  log_entry[:http]  = http unless http.empty?
  log_entry[:error] = error unless error.empty?

  JSON.generate(log_entry)
end