I am new to Service Stack and have created my first service to replace a WebAPI service. The service will be readonly and will mostly be consumed with the JsonServiceClient. I'm using version 4 of Service Stack.
I have a requirement to log several things about each request to a database - request variables (HTTP_USER_AGENT, LOGON_USER, etc.), the response code, response content type, the response time (ms), number of records returned (if applicable), etc.
I'm looking for some "global" way of achieving this (without putting a lot of code in each service/method).
Has anyone done this kind of logging before?
The best way to do this would be to use a GlobalRequestFilter and a GlobalResponseFilter which you can setup in your AppHost's Configure method. See here for more information about filtering requests.
The code below shows the basic constructs and all the data you should need about the request and response is available to you.
public override void Configure(Funq.Container container)
{
...
// Record the time the request started.
this.GlobalRequestFilters.Add((req, res, requestDto) => req.SetItem("StartTime", DateTime.Now));
// The request has been processed, ready to send response
this.GlobalResponseFilters.Add((req, res, responseDto) => {
// Get the start time that was recorded when the request started
var startTime = req.GetItem("StartTime") as DateTime;
// Determine the duration of the request
var duration = DateTime.Now - startTime;
// You can use req.Headers to access things like the HTTP_USER_AGENT
// If you are returning a IList of results then you can determine
// the number of records you are returning from the responseDto
var list = responseDTO as IList;
if(list != null){
// Response is a list
// Record the count using list.count
}
/*
* Passing additional information:
* If you need to make information from within your service methods available
* here then you can use Request.SetItem() and access it here using req.GetItem()
*/
// Save the log to the database
});
}
I hope this is a good starting point.
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