MulesoftLearning24
MulesoftLearning24

Reputation: 11

How to log string then array on one line using Mule logger component

I want to log a string using an expression like 'payload = ' + payload where payload is an array on one log line however I can't determine how to add string before the payload without it complaining about concat string and array.

Logging just an array or just a string works with no issue.

Upvotes: 1

Views: 2042

Answers (1)

aled
aled

Reputation: 25699

You can convert the array to a string, using Java convention, with the write() function. Then just use the ++ operator to concatenate. A single + is only for numeric operations, not concatenation. I used single quotes to avoid conflicts with the enclosing double quotes of the expression, however if you are using the UI editor it will take care of escaping the quotes. I'm more used to the XML view.

"#['payload=' ++ write(payload, 'application/json', {indent: false})]"

Output:

payload=[1, 2, 3, 4]

Alternatively you can use reduce() to convert the array to a string manually but 90% of the time write() will be simpler and I expect more performant:

'payload=' ++ (payload reduce ((item, accumulator="[") -> accumulator ++ (if (sizeOf(accumulator) == 1) "" else ",") ++ item as String)) ++ "]"

Upvotes: 3

Related Questions