package com.sonymusic.delphi.log4j;

import org.apache.log4j.spi.LoggingEvent;

public final class DatadogTcpSocketAppender extends AbstractTcpSocketAppender {

    public static final String API_KEY_ENV_VARIABLE = "DATADOG_API_KEY";

    private String apiKey = System.getenv(API_KEY_ENV_VARIABLE);

    @Override
    public byte[] encodeLoggingEvent(LoggingEvent loggingEvent) {
        if (apiKey == null || apiKey.isEmpty()) {
            throw new IllegalStateException("Datadog API key must be configured.");
        }

        // Datadog requires API key prepended to the message
        // https://docs.datadoghq.com/logs/log_collection/?tab=tcpussite#custom-log-forwarder
        return (apiKey + " " + getLayout().format(loggingEvent)).getBytes();
    }

    @Override
    public boolean requiresLayout() {
        return true;
    }

    public void setApiKey(String apiKey) {
        this.apiKey = apiKey;
    }
}
