Commit f5c27641 authored by Doug Barrett's avatar Doug Barrett 🔴
Browse files

perf: skip internal frames in determine_callsite

Optimize caller_locations call to skip the first 4 internal frames
by starting at frame 5 instead of frame 1. Also reduces the frame
limit from 30 to 15.

Includes fallback for shallow call stacks and test validation.

Relates-to: #60
parent 253354dd
Loading
Loading
Loading
Loading
+7 −1
Original line number Diff line number Diff line
@@ -55,8 +55,14 @@ module Labkit

        private

        # Skip internal frames (format_data, format_message, add, info) for performance.
        INTERNAL_FRAMES_TO_SKIP = 5
        MAX_FRAMES_TO_INSPECT = 15
        private_constant :INTERNAL_FRAMES_TO_SKIP, :MAX_FRAMES_TO_INSPECT

        def determine_callsite
          locations = caller_locations(1, 30) || []
          locations = caller_locations(INTERNAL_FRAMES_TO_SKIP, MAX_FRAMES_TO_INSPECT) || []
          locations = caller_locations(1, MAX_FRAMES_TO_INSPECT) || [] if locations.empty?

          locations.find do |loc|
            path = loc.path
+28 −0
Original line number Diff line number Diff line
@@ -137,6 +137,34 @@ RSpec.describe Labkit::Logging::FieldValidator::LogInterceptor do
    end
  end

  describe '#determine_callsite' do
    it 'verifies internal frame structure for INTERNAL_FRAMES_TO_SKIP constant' do
      captured_frame_labels = nil
      test_interceptor = Module.new do
        define_method(:determine_callsite) do
          captured_frame_labels = caller_locations(1, 10).map(&:label)
          super()
        end
      end

      real_logger_class = Class.new(Labkit::Logging::JsonLogger) do
        prepend Labkit::Logging::FieldValidator::LogInterceptor
      end
      real_logger_class.prepend(test_interceptor)

      output = StringIO.new
      real_logger = real_logger_class.new(output)
      real_logger.info('test')

      # Frames 0-3 are internal; frame 4 should be the actual callsite (this test)
      expect(captured_frame_labels[0]).to include('format_data')
      expect(captured_frame_labels[1]).to include('format_message')
      expect(captured_frame_labels[2]).to include('add')
      expect(captured_frame_labels[3]).to include('info')
      expect(captured_frame_labels[4]).to include('block')
    end
  end

  describe 'wrapper patterns' do
    describe '.register_wrapper_pattern' do
      after do