Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to log response body. #2

Open
gulzerr opened this issue May 16, 2024 · 3 comments
Open

How to log response body. #2

gulzerr opened this issue May 16, 2024 · 3 comments

Comments

@gulzerr
Copy link

gulzerr commented May 16, 2024

I am trying to log http request and response bodies with global middleware. Can you please tell me which property/method can return response body from the api? @ragokan

@ragokan
Copy link
Owner

ragokan commented May 16, 2024

Hello @gulzerr, for now, we don't have access to the response body on middleware, we can only use request body. The best way to do is;

function withLog(response) {
	console.log(response);
	return response;
}

// on route
return withLog(ctx.json(data))

@gulzerr
Copy link
Author

gulzerr commented May 16, 2024

Thank you for your prompt response. I will be waiting for response body in the context that I can add in global middleware

@ragokan
Copy link
Owner

ragokan commented Sep 25, 2024

Hello @gulzerr, sorry for implementing it that late but I wanted to ensure performance concerns of the app first, then do next steps.
With latest release, I added support for global context. I will update docs tomorrow/later but here is usage.

Simple example;

const responseTimeMiddleware = createMiddleware(async (ctx, next) => {
	const start = Date.now();
	// Call all next middleware and handlers.
	const response = await next();
	const time = Date.now() - start;
	console.log(`Response time for url ${ctx.req.url}: ${time}ms`);
	
	// If you call next, it is better if you send the response
	return response;
});

All examples; (cache middleware is from Bunicorn, will be in docs soon)
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants