diff --git a/lib/rackstash/logger.rb b/lib/rackstash/logger.rb index 4afcdf1..ace72b8 100644 --- a/lib/rackstash/logger.rb +++ b/lib/rackstash/logger.rb @@ -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 diff --git a/spec/rackstash/logger_spec.rb b/spec/rackstash/logger_spec.rb index 3527fb2..e7df116 100644 --- a/spec/rackstash/logger_spec.rb +++ b/spec/rackstash/logger_spec.rb @@ -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)