Skip to content

Commit

Permalink
support overriding validation schemas
Browse files Browse the repository at this point in the history
This creates a new Twiglet logger that uses a custom validation schema. This is helpful when you want to preserve configuration across loggers but use different schemas.
  • Loading branch information
chrisholmes committed Aug 9, 2024
1 parent dde2f7c commit b275e8d
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
7 changes: 7 additions & 0 deletions lib/twiglet/logger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,13 @@ def with(default_properties)
)
end

def validation_schema(validation_schema)
self.class.new(
@service_name,
**@args.merge(validation_schema: validation_schema)
)
end

def context_provider(&blk)
new_context_providers = Array(@args[:context_providers])
new_context_providers << blk
Expand Down
62 changes: 61 additions & 1 deletion test/logger_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -679,11 +679,71 @@
end
end

describe '#validation_schema' do
it 'allows for reconfiguring the validation_schema on new logger instances' do
validation_schema = <<-JSON
{
"type": "object",
"required": ["pet"],
"properties": {
"pet": {
"type": "object",
"required": ["name", "best_boy_or_girl?"],
"properties": {
"name": {
"type": "string",
"minLength": 1
},
"best_boy_or_girl?": {
"type": "boolean"
}
}
}
}
}
JSON

logger = Twiglet::Logger.new(
'petshop',
now: @now,
output: @buffer
)

message = { message: 'hi' }

pet_message = {
pet: { name: 'Davis', best_boy_or_girl?: true, species: 'dog' }
}

logger.info(message)
log = read_json(@buffer)
assert_equal 'hi', log[:message]

error = assert_raises JSON::Schema::ValidationError do
logger.info(pet_message)
end
assert_equal "The property '#/' did not contain a required property of 'message'", error.message

logger = logger.validation_schema(validation_schema)

error = assert_raises JSON::Schema::ValidationError do
logger.info(message)
end
assert_equal "The property '#/' did not contain a required property of 'pet'", error.message

logger.info(pet_message)
log = read_json(@buffer)
assert_equal 'Davis', log[:pet][:name]
end
end

private

def read_json(buffer)
buffer.rewind
JSON.parse(buffer.read, symbolize_names: true)
string = buffer.read
buffer.rewind
JSON.parse(string, symbolize_names: true)
end
end
# rubocop:enable Metrics/BlockLength

0 comments on commit b275e8d

Please sign in to comment.