Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I log requests and responses for debugging in servicestack

I would like to log the entire request & response pair for a servicestack webservice. I've looked at the response filer, however the stream exposed is read only.

like image 593
Myster Avatar asked Jul 23 '12 02:07

Myster


2 Answers

Have you seen ServiceStack's built-in Request Logger Plugin? It's a configurable In Memory, CSV or Redis Request Logger that maintains a log / (error responses) of the recent requests.

If you would like a different behaviour, you can implement and register your own IRequestLogger, it gets called for every request. It's log method gets called for every request with the following parameters.

Log(IRequest httpReq, object requestDto, object response, TimeSpan duration);

From the IRequest you can get the original .NET Core/ASP.NET/HttpListener Request / Response types with

var originalReq = httpReq.OriginalRequest;
var originalRes = httpReq.OriginalResponse;

Filtering the response

Otherwise the ways to introspect the Response is with either

  • The Response Filter or Response Filter Attributes; or
  • Overriding OnAfterExecute() on your own base class that inherits from Rest/ServiceBase
like image 138
mythz Avatar answered Oct 03 '22 10:10

mythz


This RequestFilter allows you to print raw request content. You could modify it to get more information like headers and cookies if desired. As @mythz notes in a comment, this is less detailed than the Request Logger plugin. But if you only want to add logging for a single request, it could be preferable. Disclaimer: this code is probably not production-ready and I'm not using it for production.

public class RequestDataSpyAttribute : RequestFilterAttribute
{
    // gets injected by ServiceStack
    public ILog Log { get; set; }

    private readonly string _logMessage;

    public RequestDataSpyAttribute(string logMessage)
    {
        _logMessage = logMessage;
    }

    public override void Execute(IRequest req, IResponse res, object requestDto)
    {
        System.Web.HttpRequestWrapper original = req.OriginalRequest as System.Web.HttpRequestWrapper;
        if (original == null)
            return;

        Log.Debug($"{_logMessage} Request: {original.InputStream.ReadToEnd()}");
    }
}
like image 22
Jared Beach Avatar answered Oct 03 '22 08:10

Jared Beach