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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With