From 98d022f0ee291163643bfaa731764dfd76b4cbd4 Mon Sep 17 00:00:00 2001 From: "Ben Sheldon [he/him]" Date: Mon, 25 Sep 2023 17:13:45 -0700 Subject: [PATCH] Log thread name for gem development debugging (#1085) --- spec/test_app/config/application.rb | 4 ++- spec/test_app/lib/thread_name_formatter.rb | 32 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 spec/test_app/lib/thread_name_formatter.rb diff --git a/spec/test_app/config/application.rb b/spec/test_app/config/application.rb index d194dcdac..3151908c5 100644 --- a/spec/test_app/config/application.rb +++ b/spec/test_app/config/application.rb @@ -1,10 +1,11 @@ require_relative 'boot' require 'rails/all' +require "good_job" require "good_job/engine" Bundler.require(*Rails.groups) -require "good_job" +require_relative "../lib/thread_name_formatter" module TestApp class Application < Rails::Application @@ -16,6 +17,7 @@ class Application < Rails::Application # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. # + config.log_formatter = ThreadNameFormatter.new config.active_job.queue_adapter = :good_job diff --git a/spec/test_app/lib/thread_name_formatter.rb b/spec/test_app/lib/thread_name_formatter.rb new file mode 100644 index 000000000..a9f687e5b --- /dev/null +++ b/spec/test_app/lib/thread_name_formatter.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true +class ThreadNameFormatter < ActiveSupport::Logger::SimpleFormatter + def call(severity, timestamp, _progname, message) + prefix = [emoji_hash(Thread.current.name), Thread.current.name, emoji_hash(Thread.current.name)].compact.join(" ") + "#{ActiveSupport::LogSubscriber.new.send(:color, "[#{prefix}]", :magenta)} #{super}" + end + + def emoji_hash(str) + # Hash the input string using SHA256 + digest = Digest::SHA256.hexdigest(str || "") + + # Take the first few characters from the hash + partial_digest = digest[0..4].to_i(16) + + # Define the ranges for the emojis + ranges = [ + (0x1F345..0x1F35E), # Vegetables and some other food items + (0x1F400..0x1F43E) # Animals + ] + + # Combine all ranges into a single array of code points + all_emojis = ranges.flat_map { |r| r.to_a } + + # Compute an index within the all_emojis array + index = partial_digest % all_emojis.length + + # Convert the code point to a character (emoji) + emoji = [all_emojis[index]].pack('U*') + + emoji + end +end