Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to define a custom formatter for logs #1816

Merged
merged 15 commits into from Aug 1, 2019
2 changes: 1 addition & 1 deletion 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)
Expand Down
4 changes: 4 additions & 0 deletions lib/puma/dsl.rb
Expand Up @@ -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.
#
Expand Down
4 changes: 3 additions & 1 deletion lib/puma/launcher.rb
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions test/config/custom_log_formatter.rb
@@ -0,0 +1,3 @@
log_formatter do |str|
"[#{Process.pid}] [#{Socket.gethostname}] #{Time.now}: #{str}"
end
26 changes: 26 additions & 0 deletions test/test_cli.rb
Expand Up @@ -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]
Expand Down