将Retrofit日志记录到Logback记录器中

3

我正在开发一个用于 Rest API 的 Java 客户端。我使用 Retrofit 构建客户端。我发现在创建 Retrofit 适配器时可以设置日志级别。当前所有的日志都被打印到控制台上,但是我希望将这些日志重定向到已经在应用程序中使用的 logback 生成的日志中。我该怎么做?

RestAdapter restAdapter = new RestAdapter.Builder()
                .setLogLevel(RestAdapter.LogLevel.FULL).setEndpoint(APP_URL)
                .setRequestInterceptor(new AuthRequestInterceptor())
                .setErrorHandler(new RetrofitErrorHandler()).build();

输出

---> HTTP GET http://localhost:8080/services/v1/countries
Auth-Token: ...
---> END HTTP (no body)
<--- HTTP 200 http://localhost:8080/services/v1/countries (448ms)
Transfer-Encoding: chunked
: HTTP/1.1 200 OK
Vary: Accept-Encoding
Date: Thu, 04 Jun 2015 01:36:29 GMT
Content-Type: application/json
...

<--- END HTTP (9130-byte body)

我希望所有这些都记录到日志记录器中。

1个回答

6
RestAdapter.Builder还支持使用setLog方法传递一个Log。其中,Log仅是一个接口,您可以创建自己的Logback实现并在创建RestAdapter时将其传递给构建器。
public class LogbackLog implements Log {

    public void log(String message) {
        // call logback logger from here
    }
}

Log logger = new LogbackLog();

RestAdapter restAdapter = new RestAdapter.Builder()
            .setLog(logger)
            .setLogLevel(RestAdapter.LogLevel.FULL).setEndpoint(APP_URL)
            .setRequestInterceptor(new AuthRequestInterceptor())
            .setErrorHandler(new RetrofitErrorHandler()).build();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接