diff --git a/History.md b/History.md index f1828626d8..ad105af465 100644 --- a/History.md +++ b/History.md @@ -1,7 +1,7 @@ ## Master * Features - * Your feature goes here (#Github Number) + * Add log_formatter configuration (#1816) * Bugfixes * Your bugfix goes here (#Github Number) diff --git a/lib/puma/dsl.rb b/lib/puma/dsl.rb index 87f69178f3..a6ac191a5e 100644 --- a/lib/puma/dsl.rb +++ b/lib/puma/dsl.rb @@ -282,6 +282,10 @@ def stdout_redirect(stdout=nil, stderr=nil, append=false) @options[:redirect_append] = append end + def log_formatter(&block) + @options[:log_formatter] = block + end + # Configure +min+ to be the minimum number of threads to use to answer # requests and +max+ the maximum. # diff --git a/lib/puma/launcher.rb b/lib/puma/launcher.rb index 6fd5474483..1f275f6930 100644 --- a/lib/puma/launcher.rb +++ b/lib/puma/launcher.rb @@ -63,6 +63,9 @@ def initialize(conf, launcher_args={}) @options = @config.options @config.clamp + @events.formatter = Events::PidFormatter.new if clustered? + @events.formatter = options[:log_formatter] if @options[:log_formatter] + generate_restart_data if clustered? && !Process.respond_to?(:fork) @@ -81,7 +84,6 @@ def initialize(conf, launcher_args={}) set_rack_environment if clustered? - @events.formatter = Events::PidFormatter.new @options[:logger] = @events @runner = Cluster.new(self, @events) diff --git a/test/config/custom_log_formatter.rb b/test/config/custom_log_formatter.rb new file mode 100644 index 0000000000..234748b373 --- /dev/null +++ b/test/config/custom_log_formatter.rb @@ -0,0 +1,3 @@ +log_formatter do |str| + "[#{Process.pid}] [#{Socket.gethostname}] #{Time.now}: #{str}" +end diff --git a/test/test_cli.rb b/test/test_cli.rb index 5140138665..571c7999cf 100644 --- a/test/test_cli.rb +++ b/test/test_cli.rb @@ -253,6 +253,32 @@ def test_state_file_callback_filtering assert_empty keys_not_stripped end + def test_log_formatter_default_single + cli = Puma::CLI.new [ ] + assert_instance_of Puma::Events::DefaultFormatter, cli.launcher.events.formatter + end + + def test_log_formatter_default_clustered + skip NO_FORK_MSG unless HAS_FORK + + cli = Puma::CLI.new [ "-w 2" ] + assert_instance_of Puma::Events::PidFormatter, cli.launcher.events.formatter + end + + def test_log_formatter_custom_single + cli = Puma::CLI.new [ "--config", "test/config/custom_log_formatter.rb" ] + assert_instance_of Proc, cli.launcher.events.formatter + assert_match(/^\[.*\] \[.*\] .*: test$/, cli.launcher.events.format('test')) + end + + def test_log_formatter_custom_clustered + skip NO_FORK_MSG unless HAS_FORK + + cli = Puma::CLI.new [ "--config", "test/config/custom_log_formatter.rb", "-w 2" ] + assert_instance_of Proc, cli.launcher.events.formatter + assert_match(/^\[.*\] \[.*\] .*: test$/, cli.launcher.events.format('test')) + end + def test_state url = "tcp://127.0.0.1:#{next_port}" cli = Puma::CLI.new ["--state", @tmp_path, "--control", url]