Class: JSONLogger
- Inherits:
-
Object
- Object
- JSONLogger
- Defined in:
- lib/ons-json-logger/json_logger.rb
Overview
Class that generates structured JSON log entries.
Instance Method Summary collapse
-
#initialize(application:, environment: 'development') ⇒ JSONLogger
constructor
Constructor that initialises the JSON logger.
-
#log(level:, message:, module_name:, user: {}, http: {}, error: {}) ⇒ Object
Returns a structured JSON log entry from the passed arguments.
Constructor Details
#initialize(application:, environment: 'development') ⇒ JSONLogger
Constructor that initialises the JSON logger.
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
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 |