使用翻新2进行记录

本文详细介绍了如何在Retrofit2中实现精确的日志记录,包括请求和响应的JSON内容。通过使用OkHttp的拦截器,可以有效地记录请求头、请求体及响应体等信息,提供了多种实现高级日志记录的方法。

本文翻译自:Logging with Retrofit 2

I'm trying to get the exact JSON that is being sent in the request. 我正在尝试获取在请求中发送的确切JSON。 Here is my code: 这是我的代码:

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor(){
   @Override public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
      Request request = chain.request();
      Log.e(String.format("\nrequest:\n%s\nheaders:\n%s",
                          request.body().toString(), request.headers()));
      com.squareup.okhttp.Response response = chain.proceed(request);
      return response;
   }
});
Retrofit retrofit = new Retrofit.Builder()
   .baseUrl(API_URL)
   .addConverterFactory(GsonConverterFactory.create())
   .client(client).build();

But I only see this in the logs: 但是我只在日志中看到:

request:
com.squareup.okhttp.RequestBody$1@3ff4074d
headers:
Content-Type: application/vnd.ll.event.list+json

How am I supposed to do proper logging, given the removal of setLog() and setLogLevel() which we used to use with Retrofit 1? 考虑到我们曾经使用过Retrofit 1的setLog()setLogLevel() ,我应该如何做正确的日志记录?


#1楼

参考:https://stackoom.com/question/2cqtY/使用翻新-进行记录


#2楼

hey guys,i already find solution: 大家好,我已经找到解决方法了:

  public static <T> T createApi(Context context, Class<T> clazz, String host, boolean debug) {
    if (singleton == null) {
        synchronized (RetrofitUtils.class) {
            if (singleton == null) {
                RestAdapter.Builder builder = new RestAdapter.Builder();
                builder
                        .setEndpoint(host)
                        .setClient(new OkClient(OkHttpUtils.getInstance(context)))
                        .setRequestInterceptor(RequestIntercepts.newInstance())
                        .setConverter(new GsonConverter(GsonUtils.newInstance()))
                        .setErrorHandler(new ErrorHandlers())
                        .setLogLevel(debug ? RestAdapter.LogLevel.FULL : RestAdapter.LogLevel.NONE)/*LogLevel.BASIC will cause response.getBody().in() close*/
                        .setLog(new RestAdapter.Log() {
                            @Override
                            public void log(String message) {
                                if (message.startsWith("{") || message.startsWith("["))
                                    Logger.json(message);
                                else {
                                    Logger.i(message);
                                }
                            }
                        });
                singleton = builder.build();
            }
        }
    }
    return singleton.create(clazz);
}

#3楼

I don't know if setLogLevel() will return in the final 2.0 version of Retrofit but for now you can use an interceptor for logging. 我不知道setLogLevel()是否会在Retrofit的最终2.0版本中返回,但是现在您可以使用拦截器进行记录了。

A good example can found in OkHttp wiki: https://github.com/square/okhttp/wiki/Interceptors 可以在OkHttp Wiki中找到一个很好的例子: https : //github.com/square/okhttp/wiki/Interceptors

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new LoggingInterceptor());

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://www.yourjsonapi.com")
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build();

#4楼

Try this: 尝试这个:

Request request = chain.request();
Buffer buffer = new Buffer();
request.body().writeTo(buffer);
String body = buffer.readUtf8();

After this, in the body there is the JSON you are interested in. 之后,在body中便是您感兴趣的JSON。


#5楼

Here is an Interceptor that logs both the request and response bodies (using Timber, based on an example from the OkHttp docs and some other SO answers): 这是一个记录请求和响应正文的Interceptor (使用Timber,基于OkHttp文档的示例以及其他一些SO答案):

public class TimberLoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        long t1 = System.nanoTime();
        Timber.i("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers());
        Timber.v("REQUEST BODY BEGIN\n%s\nREQUEST BODY END", bodyToString(request));

        Response response = chain.proceed(request);

        ResponseBody responseBody = response.body();
        String responseBodyString = response.body().string();

        // now we have extracted the response body but in the process
        // we have consumed the original reponse and can't read it again
        // so we need to build a new one to return from this method

        Response newResponse = response.newBuilder().body(ResponseBody.create(responseBody.contentType(), responseBodyString.getBytes())).build();

        long t2 = System.nanoTime();
        Timber.i("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers());
        Timber.v("RESPONSE BODY BEGIN:\n%s\nRESPONSE BODY END", responseBodyString);

        return newResponse;
    }

    private static String bodyToString(final Request request){

        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }
}

#6楼

For those who need high level logging in Retrofit, use the interceptor like this 对于需要在Retrofit中进行高级日志记录的用户,请使用此类拦截器

public static class LoggingInterceptor implements Interceptor {
    @Override public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long t1 = System.nanoTime();
        String requestLog = String.format("Sending request %s on %s%n%s",
                request.url(), chain.connection(), request.headers());
        //YLog.d(String.format("Sending request %s on %s%n%s",
        //        request.url(), chain.connection(), request.headers()));
        if(request.method().compareToIgnoreCase("post")==0){
            requestLog ="\n"+requestLog+"\n"+bodyToString(request);
        }
        Log.d("TAG","request"+"\n"+requestLog);

        Response response = chain.proceed(request);
        long t2 = System.nanoTime();

        String responseLog = String.format("Received response for %s in %.1fms%n%s",
                response.request().url(), (t2 - t1) / 1e6d, response.headers());

        String bodyString = response.body().string();

        Log.d("TAG","response"+"\n"+responseLog+"\n"+bodyString);

        return response.newBuilder()
                .body(ResponseBody.create(response.body().contentType(), bodyString))
                .build();
        //return response;
    }
}

public static String bodyToString(final Request request) {
    try {
        final Request copy = request.newBuilder().build();
        final Buffer buffer = new Buffer();
        copy.body().writeTo(buffer);
        return buffer.readUtf8();
    } catch (final IOException e) {
        return "did not work";
    }
}`

Courtesy : https://github.com/square/retrofit/issues/1072# 礼貌https : //github.com/square/retrofit/issues/1072#

<think>我们首先需要明确用户意图:用户希望获取手机翻新的标准操作流程(SOP)文档,或者下载资源,或者编写指南。由于SOP文档通常由企业内部制定,直接下载完整的文档可能涉及版权问题,因此更可行的是提供编写指南或框架,并指导用户如何查找相关资源。接下来,我们进行网络搜索,重点搜索手机翻新SOP的编写指南、模板或可参考的公开资源。注意,我们无法直接下载可能受版权保护的文档,但可以寻找公开的指南、框架或部分示例。搜索关键词:手机翻新标准操作流程SOP编写指南模板根据搜索结果,手机翻新SOP通常包括以下核心环节:收货检验、拆解、清洗、维修/更换部件、组装、功能测试、外观检查、包装等。不同企业可能有细微差别,但整体框架相似。因此,我们可以为用户提供一个通用的手机翻新SOP文档框架,并指导用户如何完善内容。同时,可以提示用户参考一些公开的行业标准或指南(如R2或e-Stewards认证中的相关要求)来编写符合规范的SOP。回答结构:1.概述手机翻新SOP文档的核心目的和适用范围。2.提供详细的SOP框架,包括主要步骤和每个步骤的关键控制点。3.建议参考的行业标准或认证要求。4.提供获取或编写SOP的实际操作建议(如查找模板、参考公开指南等)。注意:避免直接提供受版权保护的文档下载链接,但可以指导用户如何查找公开资源。最后,根据用户的问题和回答内容,生成相关问题。</think>### 手机翻新标准操作流程(SOP)文档指南 手机翻新SOP需涵盖数据安全、部件检测、功能测试等核心环节,以下为关键框架及资源获取方式: --- #### **一、SOP核心框架(参考ISO 9001/14001及R2认证标准)** 1. **预处理阶段** - **数据清除**:使用`Blancco`等专业工具彻底擦除原用户数据(符合NIST 800-88标准)。 - **外观分级**:按屏幕划痕、外壳磨损程度划分A/B/C级(示例标准: $$ \text{Grade A} = \{\text{划痕} \leq 0.1\text{mm}, \text{磕碰} \leq 1 \} $$ 2. **拆解与部件检测** - 电池健康检测:循环次数<500次,容量≥原规格80% - 主板功能测试:通过`3uTools`或`iMazing`进行短路/虚焊检测 ```python # 伪代码示例:电池健康算法 def battery_health(cycle_count, original_capacity): return (1 - 0.0002 * cycle_count) * original_capacity >= 0.8 * original_capacity ``` 3. **翻新操作规范** - 屏幕更换:使用无尘车间,贴合公差≤0.05mm - 防水处理:重新涂抹IP67/68级密封胶(厚度标准:$0.3\text{mm} \pm 0.05\text{mm}$) 4. **终检与认证** - 功能测试:通话、Wi-Fi、蓝牙、传感器等全项检测 - 包装要求:标注"Refurbished"及90天保修标识 --- #### **二、SOP文档获取与编写资源** 1. **免费模板下载** - [FDA翻新设备指南](https://www.fda.gov/medical-devices/refurbished-reconditioned-and-remanufactured-medical-devices)(医疗设备参考) - [Scribd手机翻新SOP模板](https://www.scribd.com/document/...)(需注册) 2. **行业标准参考** - **R2v3认证**:[可持续电子产品回收标准](https://sustainableelectronics.org/r2-standard)(含翻新流程规范) - **e-Stewards**:[责任翻新框架](https://www.estewards.org/) 3. **编写工具建议** - 使用`SweetProcess`或`Process Street`创建可视化SOP - 集成测试数据记录:`Jira Service Management`或`Zapier` --- #### **三、关键注意事项** - **法律合规**:欧盟需符合WEEE指令,美国遵循FTC翻新标签规则 - **质检设备**:推荐`MES系统`或`KeySight测试仪`实现自动化记录 - **环保要求**:废弃部件按RoHS标准处理(镉<100ppm,铅<1000ppm) > 注:直接下载完整SOP需企业授权,建议基于上述框架自定义编写,适配具体产品型号。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值