Module: Legion::Extensions::Llm::Ledger::Helpers::PersistenceLogging

Extended by:
Logging::Helper
Defined in:
lib/legion/extensions/llm/ledger/helpers/persistence_logging.rb

Constant Summary collapse

SAFE_CONTEXT_KEYS =
%i[
  uuid request_ref correlation_id correlation_ref conversation_id
  message_inference_request_id message_inference_response_id
  response_message_id provider provider_instance model_key tier
  event_id message_id tool_call_id tool_name event_type status
].freeze

Class Method Summary collapse

Class Method Details

.insert_row(db, table, attributes, operation:) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/legion/extensions/llm/ledger/helpers/persistence_logging.rb', line 22

def insert_row(db, table, attributes, operation:)
  row_id = db[table].insert(attributes)
  log.info(log_message('inserted', table, operation, row_id, attributes))
  row_id
rescue Sequel::UniqueConstraintViolation => e
  log.warn(log_message('insert_failed', table, operation, nil, attributes,
                       error_class: e.class, error: e.message))
  raise
rescue StandardError => e
  log.error(log_message('insert_failed', table, operation, nil, attributes,
                        error_class: e.class, error: e.message))
  handle_exception(e, level: :error, handled: true, operation: operation, table: table)
  raise
end

.log_message(action, table, operation, row_id, attributes, error_class: nil, error: nil) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/legion/extensions/llm/ledger/helpers/persistence_logging.rb', line 37

def log_message(action, table, operation, row_id, attributes, error_class: nil, error: nil)
  parts = {
    action:      "ledger.db.#{action}",
    table:       table,
    operation:   operation,
    row_id:      row_id,
    error_class: error_class,
    error:       error
  }.merge(safe_context(attributes)).compact

  parts.map { |key, value| "#{key}=#{value}" }.join(' ')
end

.safe_context(attributes) ⇒ Object



50
51
52
53
54
55
56
57
58
# File 'lib/legion/extensions/llm/ledger/helpers/persistence_logging.rb', line 50

def safe_context(attributes)
  attributes.each_with_object({}) do |(key, value), memo|
    normalized_key = key.to_sym
    next unless SAFE_CONTEXT_KEYS.include?(normalized_key)
    next if value.nil? || (value.respond_to?(:empty?) && value.empty?)

    memo[normalized_key] = value
  end
end