#include "logs_collector.h"

#include <library/cpp/logger/thread.h>
#include <library/cpp/logger/record.h>
#include <library/cpp/string_utils/tskv_format/builder.h>

#include <util/datetime/base.h>
#include <util/stream/str.h>

TLogsCollector::TLogsCollector(const TString& logPath, size_t queueSize)
    : Log_(new TOwningThreadedLogBackend(new TFileLogBackend(logPath), queueSize))
{
}

void TLogsCollector::CollectRequest(TStringBuf body, const TServerRequestData& reqData) {
    NTskvFormat::TLogBuilder builder("dr-log");
    builder.AddUnescaped(
            "timestamp",
            Now().FormatLocalTime("%Y-%m-%d %H:%M:%S\ttimezone=%z"))
        .Add("addr", reqData.HeaderInOrEmpty("X-Forwarded-For-Y"))
        .Add("user-agent", reqData.HeaderInOrEmpty("User-Agent"))
        .Add("content", body)
        .Add("path", reqData.ScriptName())
        .End();
    const TString& logLine = builder.Str();
    try {
        Log_->WriteData(TLogRecord(TLOG_INFO, logLine.Data(), logLine.Size()));
    } catch(...) {
    }
}

void TLogsCollector::ReopenLog() {
    Log_->ReopenLog();
}
