Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # So I needed to catch the logs on a certain action when a certain condition is met.
- # I am a bit lazy to find solutions or gems for this and there probably is.
- # I decided to create order of logic:
- # I will have a method for setting if the recording should start, and a method if recording should stop
- # I will need a variable to store the recorded items and a method to retrieve it.
- module LogRecorder
- RECORD_LIMIT = 1_000
- def started_recording?
- Thread.current[:buffers].is_a?(Array)
- end
- def start_recording
- Thread.current[:buffers] = []
- started_recording?
- end
- def recorded_logs
- Thread.current[:buffers]
- end
- def end_recording
- Thread.current[:buffers] = nil
- !started_recording?
- end
- def add(*args)
- if started_recording?
- buffer_severity = args[0] || UNKNOWN
- buffer_progname = args[1] || @progname
- buffer_message = if args[2].nil?
- if block_given?
- yield
- else
- buffer_progname = @progname
- buffer_progname
- end
- else
- args[2]
- end
- formatted_message = format_message(format_severity(buffer_severity), Time.now, buffer_progname, buffer_message)
- add_log_record("#{Time.now} -- #{format_severity(buffer_severity).rjust(5, ' ')} | #{formatted_message}")
- end
- super
- end
- private
- def add_log_record(item)
- return if Thread.current[:buffers].last == item # just to check that it doesnt double log
- Thread.current[:buffers] = (Thread.current[:buffers] + [item]).last(RECORD_LIMIT) if started_recording?
- end
- end
- # I then added the following line of code to a file in rails initializers:
- Rails.logger.class.prepend(LogRecorder)
- # I previously thought of adding a method like silence. But I decided otherwise so I dont need to put things in a block.
- # A potential danger maybe is having the buffer to grow into a very large size. Thus, the method :add_log_record
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement