ubicloud/lib/clog.rb
Enes Cakir 0ed343b660 Allow to log additional fields with models in clog
Sometimes, the model data is insufficient, and we may need to add extra
fields to the clog's metadata. The new array metadata feature achieves
this.

When the metadata is an array, it parses each element sequentially. If
the element is a Sequel::Model, it obtains its clog representation,
similar to the previous commit. If the element is a hash, it merges with
the intermediate hash.

For example, `[strand, {field1: "a", field2: "b"}]` expands to `{strand:
{id: 123, label: "start"}, field1: "a", field2: "b"}`.
2024-07-12 13:43:30 +03:00

51 lines
1.1 KiB
Ruby

# frozen_string_literal: true
require "json"
class Clog
@@mutex = Mutex.new
def self.emit(message)
out = if block_given?
case metadata = yield
when Hash
metadata
when Array
metadata.reduce({}) do |hash, item|
case item
when Hash
hash.merge(item)
when Sequel::Model
hash.merge(serialize_model(item))
else
hash.merge({invalid_type: item.class.to_s})
end
end
when Sequel::Model
serialize_model(metadata)
else
{invalid_type: metadata.class.to_s}
end
else
{}
end
return if Config.test?
out[:message] = message
out[:time] = Time.now
if (thread_name = Thread.current.name)
out[:thread] = thread_name
end
raw = (JSON.generate(out) << "\n").freeze
@@mutex.synchronize do
$stdout.write(raw)
end
nil
end
private_class_method def self.serialize_model(model)
{model.class.table_name => model.values.except(*model.class.redacted_columns)}
end
end