Search code examples
c#servicestack.net-8.0

How do you change the default logging of JsonApiClient?


I am using the ServiceStack JsonApiClient to make service requests.

When the JsonApiClient encounters a non successful status code i.e. 500, it automatically (and rightly) logs at error level to my console or to the logs using the standard ILoggerFactory like so:

fail: ServiceStack.JsonApiClient[0]
      SendAsync: InternalServerError
      500 InternalServerError
Code: InternalServerError, Message: InternalServerError

My problem is that the same thing seems to happen when a 400 series error is encountered (as far as I am concerned - these are generally client issues, not server side issues).

fail: ServiceStack.JsonApiClient[0]
      SendAsync: NotFound
      404 NotFound
Code: NotFound, Message: NotFound

So if a GET request is processed, and the result is not found, I would expect that a valid response to the consumer of my API would be a 404. I really don't want / need this logged as an error, because it is expected behaviour.

This is the code (minimum viable reproduction of the problem) I used in a standard ServiceStack service to re-create this error - the same behaviour happens if this happens across services, and the error is logged by the JsonApiClient in the first service method. Both the requests and the responses have no implementation - the request implements IReturn<TResponse> and the response implements IHasResponseStatus and IHasStatusCode

public async Task<TestGetResponse> Get(TestGetRequest request)
{
  JsonApiClient client = new JsonApiClient("http://localhost:8080");
  Task<TestGetRequest2> response = client.SendAsync<TestGetRequest2>(new TestGetRequest2());
            
  return new TestGetResponse { StatusCode = 200 };
}

public async Task<TestGetResponse2> Get(TestGetRequest2 request)
{
  return new TestGetResponse2 { StatusCode = 404 };
}

My question is - how do I stop the JsonApiClient from logging at error level for 400 series response codes? Ideally, I'd still like to log these, but at a different level (maybe info or warning).

I've tried hooking into the ExceptionFilter by adding a delegate to this method, but I don't seem to be able to affect the logging (unless I am doing something wrong!).

My logs are getting flooded with a lot of noise in a busy production system, and 'real' errors (the 500 series errors) are getting obfuscated.

Any help or pointers would be very much appreciated.


Solution

  • All Exceptions in JsonApiClient are logged as errors with Exceptions where if you're using ASP .NET Core it will use ASP .NET Core's ILoggerFactory whose Exception logging is conceptually similar to:

    var log = loggerFactory.CreateLogger(typeof(JsonApiClient));
    log.LogError(default(EventId), exception, message);
    

    Which will allow you to use ASP .NET's Core logging filtering system to filter logging which is logged against the JsonApiClient type.

    In addition you could use a decorator pattern to have JsonApiClient use a custom logger that you can control what get logs in your AppHost, e.g:

    public override void Configure()
    {
        LogManager.LogFactory = new MyLoggingFactory(LogManager.LogFactory);
    }
    

    Where MyLoggingFactory just returns a custom logger for JsonApiClient, e.g:

    public class MyLoggingFactory(ILogFactory source) : ILogFactory
    {
        public ILog GetLogger(Type type)
        {
            var log = source.GetLogger(type);
            return type == typeof(JsonApiClient) 
                ? new MyLogger(log) 
                : log;
        }
        public ILog GetLogger(string typeName) => source.GetLogger(typeName);
    }
    

    Your custom logger can inspect the Exception and error message to ignore logging, otherwise calls the underlying logging provider, e.g:

    public class MyLogger(ILog log) : ServiceStack.Logging.ILog
    {
        public void Error(object message, Exception exception)
        {
            if (IgnoreException(message,exception)) return;
            log.Error(message, exception);
        }
        public void Error(object message) => log.Error(message);
        public void ErrorFormat(string format, params object[] args) => log.ErrorFormat(format, args);
        public void Debug(object message) => log.Debug(message);
        public void Debug(object message, Exception exception) => log.Debug(message, exception);
        public void DebugFormat(string format, params object[] args) => log.DebugFormat(format, args);
        public void Fatal(object message) => log.Fatal(message);
        public void Fatal(object message, Exception exception) => log.Fatal(message);
        public void FatalFormat(string format, params object[] args) => log.FatalFormat(format, args);
        public void Info(object message) => log.Info(message);
        public void Info(object message, Exception exception) => log.Info(message, exception);
        public void InfoFormat(string format, params object[] args) => log.InfoFormat(format, args);
        public void Warn(object message) => log.Warn(message);
        public void Warn(object message, Exception exception) => log.Warn(message, exception);
        public void WarnFormat(string format, params object[] args) => log.WarnFormat(format, args);
        public bool IsDebugEnabled => log.IsDebugEnabled;
    }