|
| 1 | +# typed: true |
| 2 | +# frozen_string_literal: true |
| 3 | + |
| 4 | +require "test_helper" |
| 5 | +require "open3" |
| 6 | +require "timeout" |
| 7 | + |
| 8 | +# Test that rake tasks in production have working logs when LogStruct auto-disables. |
| 9 | +class RakeTaskLoggingTest < ActiveSupport::TestCase |
| 10 | + def test_rake_task_in_production_has_clean_logs |
| 11 | + # Simulate production rake task: |
| 12 | + # - RAILS_ENV=production (LogStruct would enable for servers) |
| 13 | + # - NOT a server process (rake task) |
| 14 | + # - LogStruct should auto-disable and fall back to clean Rails logging |
| 15 | + env = { |
| 16 | + "RAILS_ENV" => "production" |
| 17 | + # Don't set LOGSTRUCT_ENABLED - let auto-detection handle it |
| 18 | + # Rake tasks should auto-disable because no server is detected |
| 19 | + } |
| 20 | + |
| 21 | + # Run a rake task that logs something |
| 22 | + cmd = ["bundle", "exec", "rake", "logging:test_output"] |
| 23 | + |
| 24 | + stdout_output = nil |
| 25 | + stderr_output = nil |
| 26 | + |
| 27 | + Open3.popen3(env, *cmd, chdir: Rails.root.to_s) do |_stdin, stdout, stderr, wait_thr| |
| 28 | + begin |
| 29 | + Timeout.timeout(30) do |
| 30 | + wait_thr.value |
| 31 | + end |
| 32 | + rescue Timeout::Error |
| 33 | + begin |
| 34 | + Process.kill("TERM", wait_thr.pid) |
| 35 | + rescue |
| 36 | + nil |
| 37 | + end |
| 38 | + |
| 39 | + flunk "Rake task timed out" |
| 40 | + end |
| 41 | + |
| 42 | + stdout_output = stdout.read |
| 43 | + stderr_output = stderr.read |
| 44 | + end |
| 45 | + |
| 46 | + combined_output = "#{stdout_output}\n#{stderr_output}" |
| 47 | + |
| 48 | + # Should NOT have hybrid format like: {message: "...", tags: [...]} |
| 49 | + # This pattern indicates the TaggedLogging monkey patch is wrapping |
| 50 | + # messages in hashes but they're not going through JSON formatter |
| 51 | + hybrid_pattern = /\{message:\s*["'].*["'],\s*tags:/ |
| 52 | + |
| 53 | + refute_match hybrid_pattern, |
| 54 | + combined_output, |
| 55 | + "Found hybrid log format - LogStruct is half-enabled!\n" \ |
| 56 | + "This means TaggedLogging monkey patch is active but SemanticLogger is not.\n" \ |
| 57 | + "Output:\n#{combined_output}" |
| 58 | + |
| 59 | + # Should have the exact log messages (not silently dropped) |
| 60 | + assert_includes combined_output, |
| 61 | + "Test log message from rake task", |
| 62 | + "Expected to see 'Test log message from rake task' but logs appear to be dropped.\n" \ |
| 63 | + "Output:\n#{combined_output}" |
| 64 | + |
| 65 | + # Should have the [custom_tag] prefix in clean Rails format |
| 66 | + assert_match(/\[custom_tag\].*Tagged test log message/, |
| 67 | + combined_output, |
| 68 | + "Expected to see '[custom_tag] Tagged test log message' in clean Rails format.\n" \ |
| 69 | + "Output:\n#{combined_output}") |
| 70 | + end |
| 71 | +end |
0 commit comments