how do I log requests and responses for debugging in servicestack

Viewed 5130

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.

2 Answers

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()}");
    }
}
Related