Logging Function Parameters

aliak something at something.com
Sun Mar 18 22:57:15 UTC 2018


On Saturday, 17 March 2018 at 10:34:41 UTC, dom wrote:
> Hi,
>
> I am looking for a method to log the current function name + 
> parameters.
> Getting the name of the current function is simply possible 
> with __PRETTY_FUNCTION__
> Is there some possibility to generically access the parameters 
> of a function such that they can be iterated and printed out?
>
> currently i have something like this:
> log.info(__PRETTY_FUNCTION__,  " ", parameter1, " ", 
> parameter2);
>
> i would like to get to something like that:
> log.info(__PRETTY_FUNCTION__,  " ", parameters.join(", "));

You may be able to do something with a mixin. I tried this but I 
think I'm hitting a compiler bug, or I'm just using mixins wrong.

import std.stdio;

string arguments(alias f)() {
     import std.meta: AliasSeq;
     import std.traits: ParameterIdentifierTuple;
     import std.array: join;
     string[] args;
     foreach (a; [AliasSeq!(ParameterIdentifierTuple!f)]) {
         args ~= `"` ~ a ~ `: ", ` ~ a;
     }
     return args.join(`, ", ", `);
}

// calling writeln(mixin(arguments!f)) should do what you want.

void f(int a, int b, int c) {

     // But you get a:
     // Error: Using the result of a comma expression is not 
allowed
     // writeln(mixin(arguments!f));


     auto value = arguments!f; // "a: ", a, ", ", "b: ", b, ", ", 
"c: ", c
     writeln(value);

     // This is ok:
     writeln("a: ", a, ", ", "b: ", b, ", ", "c: ", c);
}

void main() {
  	f(1, 2, 3);
}

You might be able to start with that and get something that 
works. Or maybe someone knows how to make the mixin part above 
compile. I have a feeling you may need to make the arguments() 
function return a string("p0: ", arg0, ", p1: ", arg1" ...) 
instead so that it's a full string instead of a comma separated 
expression maybe.

Cheers


More information about the Digitalmars-d-learn mailing list