Skip to content

Commit

Permalink
Merge pull request #333 from interagent/replace-newlines-in-log-strings
Browse files Browse the repository at this point in the history
Replace newlines in log strings
  • Loading branch information
beanieboi authored Dec 14, 2020
2 parents 3639d11 + 3a3efea commit 286fb53
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 9 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p

## [0.28.0] - 2020-05-06
### Changed
- Ensure newline characters are removed from log strings. ([]())
- Ensure all strings with spaces are quoted in logs. ([#332](https://github.com/interagent/pliny/pull/332))
- Allow ActiveSupport 5 or 6. ([#331](https://github.com/interagent/pliny/pull/331))

Expand Down
21 changes: 12 additions & 9 deletions lib/pliny/log.rb
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,17 @@ def log_to_stream(stream, data, &block)
end
end

def quote_string(k, v)
def replace_newlines(v)
v.gsub("\n", "\\n")
end

def quote_string(v)
if !v.include?('"')
%{#{k}="#{v}"}
%{"#{v}"}
elsif !v.include?("'")
%{#{k}='#{v}'}
%{'#{v}'}
else
%{#{k}="#{v.gsub(/"/, '\\"')}"}
%{"#{v.gsub(/"/, '\\"')}"}
end
end

Expand All @@ -150,11 +154,10 @@ def unparse_pair(k, v)
"#{k}=#{v.iso8601}"
else
v = "#{v}"
if v =~ /\s/
quote_string(k, v)
else
"#{k}=#{v}"
end
v = replace_newlines(v)
v = quote_string(v) if v =~ /\s/

"#{k}=#{v}"
end
end
end
Expand Down
6 changes: 6 additions & 0 deletions spec/log_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,12 @@
Pliny.log(foo: "string with spaces")
end

it "replaces newlines in strings" do
expect(@io).to receive(:print).with("foo=\"string\\nwith newlines\\n\"\n")

Pliny.log(foo: "string\nwith newlines\n")
end

it "by default interpolates objects into strings" do
expect(@io).to receive(:print).with("foo=message\n")
expect(@io).to receive(:print).with("foo=42\n")
Expand Down

0 comments on commit 286fb53

Please sign in to comment.