Advertisement
Guest User

Untitled

a guest
Oct 25th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. # So I needed to catch the logs on a certain action when a certain condition is met.
  2. # I am a bit lazy to find solutions or gems for this and there probably is.
  3. # I decided to create order of logic:
  4. # I will have a method for setting if the recording should start, and a method if recording should stop
  5. # I will need a variable to store the recorded items and a method to retrieve it.
  6.  
  7. module LogRecorder
  8. RECORD_LIMIT = 1_000
  9.  
  10. def started_recording?
  11. Thread.current[:buffers].is_a?(Array)
  12. end
  13.  
  14. def start_recording
  15. Thread.current[:buffers] = []
  16. started_recording?
  17. end
  18.  
  19. def recorded_logs
  20. Thread.current[:buffers]
  21. end
  22.  
  23. def end_recording
  24. Thread.current[:buffers] = nil
  25. !started_recording?
  26. end
  27.  
  28. def add(*args)
  29. if started_recording?
  30. buffer_severity = args[0] || UNKNOWN
  31. buffer_progname = args[1] || @progname
  32. buffer_message = if args[2].nil?
  33. if block_given?
  34. yield
  35. else
  36. buffer_progname = @progname
  37. buffer_progname
  38. end
  39. else
  40. args[2]
  41. end
  42.  
  43. formatted_message = format_message(format_severity(buffer_severity), Time.now, buffer_progname, buffer_message)
  44.  
  45. add_log_record("#{Time.now} -- #{format_severity(buffer_severity).rjust(5, ' ')} | #{formatted_message}")
  46. end
  47.  
  48. super
  49. end
  50.  
  51. private
  52. def add_log_record(item)
  53. return if Thread.current[:buffers].last == item # just to check that it doesnt double log
  54. Thread.current[:buffers] = (Thread.current[:buffers] + [item]).last(RECORD_LIMIT) if started_recording?
  55. end
  56. end
  57.  
  58.  
  59.  
  60. # I then added the following line of code to a file in rails initializers:
  61.  
  62. Rails.logger.class.prepend(LogRecorder)
  63.  
  64.  
  65. # I previously thought of adding a method like silence. But I decided otherwise so I dont need to put things in a block.
  66. # 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