How to pass a logger to logRequests in dart shelf?

Issue

I’m trying to use the logRequests function from shelf. Function is as follows:

Middleware logRequests(
    {void logger(String message, bool isError)?}
)

And implementation is like:

Middleware logRequests({void Function(String message, bool isError)? logger}) => ...

I’m calling logRequests here:

final handler = Pipeline().addMiddleware(logRequests()).addHandler(app);

And it works fine, but I want that optional logger function so I can do whatever I want with the messages.
Problem is I can’t seem to be able to pass a function as the argument here… I’ve searched how to pass functions as arguments but all I get is "Too many positional arguments: 0 expected, but 1 found".

I’ve tried define the function in a lot of ways, the last one (as seen in the answer here) was:

void Function(String s, bool b) log() => (String s, bool b) => print('');

And calling it like:

final handler = Pipeline().addMiddleware(logRequests(log)).addHandler(app);

This and all the other things I’ve tried always gives me above mentioned error.

So how can I pass a function here?

Thanks

Solution

So, after trying more things, found how to do it.

Function:

void _log(String msg, bool isError){ print('test Logger'); }

Calling it:

final handler = Pipeline().addMiddleware(logRequests(logger: _log)).addHandler(app);

Answered By – jRicardo

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *