1
0
mirror of https://github.com/meineerde/rackstash.git synced 2025-10-17 14:01:01 +00:00

Add Logger#[] and Logger#[]= alias methods to get and set fields

This commit is contained in:
Holger Just 2017-07-25 00:03:47 +02:00
parent 12261ef786
commit f92bde5af2
2 changed files with 48 additions and 0 deletions

View File

@ -83,6 +83,28 @@ module Rackstash
msg
end
# Retrieve a stored value from a given `key` in the current Buffer's fields.
# This is strictly equivalent to calling `logger.fields[key]`.
#
# @param (see Fields::Hash#[])
# @return (see Fields::Hash#[])
def [](key)
buffer.fields[key]
end
# Set the value of a key in the current Buffer's fields to the supplied
# value. You can set nested hashes and arrays here. The hash keys will be
# normalized as strings.
# This is strictly equivalent to calling `logger.fields[key] = value`.
#
# @param (see Fields::Hash#[]=)
# @raise [ArgumentError] if you attempt to set one of the forbidden fields,
# namely any of {Buffer::FORBIDDEN_FIELDS}
# @return (see Fields::Hash#[]=)
def []=(key, value)
buffer.fields[key] = value
end
# Set the base log level as either one of the {SEVERITIES} or a
# String/Symbol describing the level. When logging a message, it will only
# be added if its log level is at or above the base level defined here

View File

@ -38,6 +38,32 @@ describe Rackstash::Logger do
end
end
describe 'subscript accessors' do
it 'gets a fields from the current Buffer' do
logger['key'] = 'value'
expect(logger['key']).to eql 'value'
end
it 'normalizes keys when setting values' do
logger[:foo] = 'foo value'
expect(logger['foo']).to eql 'foo value'
logger[42] = '42 value'
expect(logger['42']).to eql '42 value'
end
it 'returns nil if a value was not set' do
expect(logger['missing']).to be_nil
end
it 'can\'t set forbidden values' do
expect { logger['message'] = 'nope' }.to raise_error ArgumentError
expect { logger['tags'] = 'nope' }.to raise_error ArgumentError
expect { logger['@timestamp'] = 'nope' }.to raise_error ArgumentError
expect { logger['@version'] = 'nope' }.to raise_error ArgumentError
end
end
describe '#close' do
it 'forwards to the sink' do
expect(logger.sink).to receive(:close)