Search

Dark theme | Light theme

April 7, 2023

DataWeave Delight: Using The log Function

The log function in the dw::Core module allows to log a value or an expression. The function returns the input unchanged. This means we can wrap our code with the log function and the code is still executed as is, but also logged in a system log. As an extra argument we can specify a String value that will be a prefix to the expression value in the logging output. The fact that the input is also returned makes it very easy to add the log function to our DataWeave expressions.

In the following example we use the log function for several use cases:

Source

%dw 2.0

import upper from dw::core::Strings

// Sample object we want to use for logging.
var user = {
    alias: "mrhaki",
    name: {
        firstName: "Hubert",
        lastName: "Klein Ikkink"
    }
}

output application/json
---
{
    // Log a value.
    logValue: log("DataWeave"),

    // Log expression.
    logUpper: log(upper("DataWeave")),

    // Log object property.
    logExpr: log(user.alias),

    // Log with prefix.
    logExprWithPrefix: log("alias", user.alias),

    // Log object.
    logName: log("name", user.name)
}

Output

{
  "logValue": "DataWeave",
  "logUpper": "DATAWEAVE",
  "logExpr": "mrhaki",
  "logExprWithPrefix": "mrhaki",
  "logName": {
    "firstName": "Hubert",
    "lastName": "Klein Ikkink"
  }
}

We see the output simply returns the original object that we passed to the log function. But when we look at a log viewer, for example the console of a Mule application, we see a representation of the object. And if we specified a prefix the prefix is also visible in the logging output.

The previous code returns the following log output:

"DataWeave"
"DATAWEAVE"
"mrhaki"
alias - "mrhaki"
name - { firstName: "Hubert", lastName: "Klein Ikkink" }

Written with DataWeave 2.4.