Home

Any way to log parameter values for methods defined in LinqPad? (without hardcoding parameter names)

edited April 2022

I'd like to be able to apply logging (of parameter values) to methods defined within LinqPad, is there some magic way to do this?

I've looked into using metalama (postsharp), but this will not work since LinqPad scripts are compiled with Roslyn.

I've already discussed with the metalama dev, Gael, but can't figure out a workaround for a solution outside of Linqpad - was wondering if there is something I can do within LinqPad to achieve parameter logging.

Here's what I'm trying to do - (stackoverflow question)

Thanks!

Comments

  • In terms of other solutions for logging, there are functional approaches, which work well on the call-side:

    void Main()
    {
        Log (() => TestMethod ("Sdf"));
    }
    
    string TestMethod (string x)
    {   
        Console.WriteLine ("Hello, " + x);
        return x;
    }
    
    T Log<T> (Expression<Func<T>> e)
    {
        // You could wrap this around try/catch if required...
        T returnValue = e.Compile()();
    
        if (e.Body is MethodCallExpression me)
            new { me.Arguments, returnValue }.Dump (me.Method.Name);
    
        return returnValue;
    }
    
  • edited April 2022

    Hi Joe, thank you very much for this approach. This is a nice little workaround - I have just learned about Expressions today!

    I'm going to add a bit to the code you provided to get the arg names and to evaluate the argument values - pieced together with the help of StackOverflow users.

    Thanks again!

    T Log<T>(Expression<Func<T>> e)
    {
        T returnValue = e.Compile()();
    
        if (e.Body is MethodCallExpression me)
        {
            new
            {
                ArgNames = me.Method.GetParameters().Select(x => new { Type = x.ParameterType.FullName, x.Name }),
                Values = me.Arguments.Select(x => GetValue(x)),
                ArgTypes = me.Method.ToString()
            }.Dump(me.Method.Name);
        }
    
        return returnValue;
    }
    
    private object GetValue(Expression member)
    {
        var objectMember = Expression.Convert(member, typeof(object));
        var getterLambda = Expression.Lambda<Func<object>>(objectMember);
    
        var getter = getterLambda.Compile();
    
        return getter();
    }
    

Sign In or Register to comment.