/*
 * SPDX-FileCopyrightText: 2000-2002 Copyright LifeLine Networks BV (www.lifeline.nl)
 * SPDX-FileCopyrightText: 2000-2002 Copyright Bastiaan Bakker
 * SPDX-FileCopyrightText: 2004 Copyright contributors to the cppTango project
 *
 * SPDX-License-Identifier: LGPL-3.0-or-later
 */

#include <tango/common/log4tango/XmlLayout.h>

#include <tango/common/log4tango/LoggingEvent.h>
#include <tango/common/log4tango/Portability.h>

#include <chrono>
#include <cstdio>
#include <sstream>
#include <string>

namespace log4tango
{

XMLLayout::XMLLayout()
{
    // no-op
}

XMLLayout::~XMLLayout()
{
    // no-op
}

std::string XMLLayout::format(const LoggingEvent &event)
{
    auto id = []() -> std::string
    {
        std::ostringstream out;
        out << std::this_thread::get_id();
        return out.str();
    };

    auto ts = [](const LoggingEvent &event) -> std::string
    {
        std::ostringstream out;
        auto ts_ms = std::chrono::duration_cast<std::chrono::milliseconds>(event.timestamp.time_since_epoch()).count();
        out << ts_ms;
        return out.str();
    };

    std::string buf;
    buf.append("<log4j:event logger=\"");
    buf.append(event.logger_name);
    buf.append("\" timestamp=\"");
    buf.append(ts(event));
    buf.append("\" level=\"");
    buf.append(log4tango::Level::get_name(event.level));
    buf.append("\" thread=\"");
    buf.append(id());
    buf.append("\">\r\n");
    buf.append("<log4j:message><![CDATA[");
    buf.append(event.message);
    buf.append("]]></log4j:message>\r\n");
    buf.append("<log4j:NDC><![CDATA[");
    buf.append("]]></log4j:NDC>\r\n");
    buf.append("</log4j:event>\r\n\r\n");
    return buf;
}

} // namespace log4tango
