Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging lambda expressions

Tags:

c#

lambda

public class Demo
{       
    public void When(Func<Person, bool> condition)
    {
        if (!condition)
        {
            Log.Info("Condition not met.");
            return;
        }

        // Do something
    }
}

In the When method, I would like to log when a predicate or Func<bool> returns false. However, just logging "condition not met" doesn't give me much information. If I call the method like so:

demo.When(x => x.Name == "John");

Is there a way to convert that expression into a readable/meaningful string for logging purposes?

like image 862
nivlam Avatar asked Mar 29 '12 18:03

nivlam


People also ask

How do you log a Lambda function?

You can use the Amazon CloudWatch console to view logs for all Lambda function invocations. Open the Log groups page on the CloudWatch console. Choose the log group for your function (/aws/lambda/ your-function-name ). Choose a log stream.

What does Lambda logging include?

Your Lambda function comes with a CloudWatch Logs log group and a log stream for each instance of your function. The Lambda runtime environment sends details about each invocation to the log stream, and relays logs and other output from your function's code.

Can I console log in Lambda?

Using the Lambda consoleYou can use the Lambda console to view log output after you invoke a Lambda function. For more information, see Accessing Amazon CloudWatch logs for AWS Lambda.


1 Answers

There's not much useful meta data in an ordinary lambda. You could use expression trees instead:

void When(Expression<Func<Person, bool>> condition)
{
    var person = new Person();
    if (!condition.Compile()(person))
    {
        Console.WriteLine("Condition not met: " + condition);
        return;
    }
}

Then at the call site:

 When(x => false);

And the output will be:

Condition not met: x => False

However, expression trees introduce a lot more overhead, and condition.Compile is not cheap either. So I can't generally recommend this approach, but it will output useful info like you want.

like image 182
Kirk Woll Avatar answered Oct 19 '22 22:10

Kirk Woll