#pragma once

#include <balancer/kernel/module/iface.h>

#include <library/cpp/logger/log.h>

namespace NSrvKernel {
    namespace NLogImpl {
        template<class TLe>
        inline void DoPrintRemoteAddr(TLe&& out, const TConnDescr& descr) {
            out << descr.RemoteAddrPortStr();
        }

        template<class TLe>
        inline void DoPrintNow(TLe&& out, TInstant now) {
            out << now.ToStringLocal();
        }

        template<class TLe>
        inline void DoPrintModule(TLe&& out, ELogPriority logLevel, TStringBuf name) {
            out << name << " [" << (int)logLevel << ']';
        }

        template<class TLe>
        inline auto DoPrintErrorLogPrefix(TLe&& out, ELogPriority logLevel, TStringBuf name, const TConnDescr& descr) {
            DoPrintRemoteAddr(out, descr);
            out << '\t';
            DoPrintNow(out, Now());
            out << '\t';
            DoPrintModule(out, logLevel, name);
            out << '\t';
            return std::forward<TLe>(out);
        }
    }
}


#define Y_HTTPD_LOG_IMPL(logPtr, level, name, descr, message) \
    if (logPtr && logPtr->DefaultPriority() >= level) try { \
        NLogImpl::DoPrintErrorLogPrefix(*logPtr << (level), level, name, descr) << message << '\n'; \
    } catch (...) {}

#define LOG_ERROR(level, descr, message) Y_HTTPD_LOG_IMPL(descr.ErrorLog, level, NAME, descr, message)
