You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NLOG无法记录HTTP请求返回字符串问题排查

无法用NLOG记录HTTP请求返回的字符串

我用NLOG记录HTTP请求返回的字符串时遇到了问题,相关代码如下:

HttpResponseMessage res = client.PostAsync(path, content).Result;

if (!res.IsSuccessStatusCode)
{
    if (File.Exists(tempFilePath))
        File.Delete(tempFilePath);
    String responseStr = res.Content.ReadAsStringAsync().Result;
    //TODO(nassim) : Remplacé ce try catch par juste un retour d'erreur dans les log

    //ErrorReponse error = JsonConvert.DeserializeObject<ErrorReponse>(responseStr);
    Logger.Debug("Taille du log : " + responseStr.Length);
    if(responseStr.Length > 200)
    {
        Logger.Debug(" 1");
        Logger.Error("Erreur d'envoi de Document a Recital : " + responseStr.Substring(0, 200));
    }
    else
    {
        Logger.Debug(" 2");
        Logger.Error("Erreur d'envoi de Document a Recital : " + responseStr.Substring(0, 10));
    }

    if (responseStr.Contains("Invalid credentials.") || responseStr.Contains("Token is expired."))
    {
        refreshToken(vault, storedValues);
        storeDocInReciTAL(env);
    }
    throw new Exception("Erreur d'envoi du document vers reciTAL.");
}

附带的堆栈跟踪如下:
NLOG日志缺失的堆栈跟踪

可以看到拼接responseStr的日志行完全没有显示,起初我以为是字符串过长,但实际上该字符串仅37个字符,请问我哪里操作出错了?


问题排查与解决

1. 检查NLOG的日志级别配置

代码里用了Logger.Debug输出长度和分支标记,如果NLOG配置文件中Debug级别未启用(比如最低日志级别设为Info或更高),这些Debug日志会被直接过滤。另外要确认Error级别的日志是否被配置的输出目标(文件、控制台等)接收,比如有没有在规则里排除了Error级别的日志。

2. 更换日志写法,避免直接字符串拼接

直接拼接字符串可能因为responseStr中包含特殊字符(如换行、不可见控制字符)导致日志输出异常,建议改用NLOG的结构化日志方式:

// 短字符串场景直接输出完整内容
Logger.Error("Erreur d'envoi de Document a Recital : {ResponseContent}", responseStr);
// 按原逻辑截取的写法
Logger.Error("Erreur d'envoi de Document a Recital : {ResponseContent}", responseStr.Substring(0, 10));

结构化日志会自动处理特殊字符,同时也更利于后续的日志分析。

3. 确保日志写入完成再抛出异常

NLOG默认采用异步写入模式,如果在日志输出后立刻抛出异常终止线程,可能导致日志还没来得及写入缓存就被中断。可以在抛出异常前强制刷新日志:

// 刷新所有日志缓存,确保写入完成
Logger.Flush();
throw new Exception("Erreur d'envoi du document vers reciTAL.");

4. 验证responseStr的实际内容

虽然你说字符串长度是37,但可以先通过控制台输出确认内容是否正常:

Console.WriteLine("Response内容: " + responseStr);
Console.WriteLine("Response字符编码: " + res.Content.Headers.ContentEncoding);

排查是否存在编码问题(比如返回内容是非UTF-8编码但被强制按UTF-8读取),或者字符串中包含大量不可见字符,导致NLOG无法正常解析输出。


内容的提问来源于stack exchange,提问作者Amaury Bianchi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 23:25:57