DefaultLogEvent.java

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.maven.logging.impl;

import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.maven.api.logging.LogEvent;
import org.apache.maven.api.logging.LogLevel;
import org.apache.maven.api.logging.LoggerManager;

/**
 * Effectively immutable implementation of {@link LogEvent} with lazy formatting.
 * <p>
 * All fields are set at construction time and never mutated, except for
 * {@link #message()} and {@link #renderedLine()}, which are computed lazily
 * on first access via volatile write-once fields. The class is therefore
 * safe to share across threads despite not being strictly immutable.
 *
 * @since 4.2.0
 */
public final class DefaultLogEvent implements LogEvent {

    private final Instant timestamp;
    private final LogLevel level;
    private final String message;
    private final String loggerName;
    private final Throwable throwable;
    private final String sourceClassName;
    private final String sourceMethodName;
    private final long threadId;
    private final long sequenceNumber;
    private final String threadName;
    private final String projectId;
    private final String mojoId;
    private final String pluginId;
    private final Map<String, Object> keyValues;
    private final String messageTemplate;
    private final Object[] messageArgs;
    private volatile String renderedLine;

    private volatile String formattedMessage;
    private volatile List<Object> messageArgsList;

    @SuppressWarnings("checkstyle:ParameterNumber")
    public DefaultLogEvent(
            Instant timestamp,
            LogLevel level,
            String message,
            String loggerName,
            Throwable throwable,
            String sourceClassName,
            String sourceMethodName,
            long threadId,
            long sequenceNumber,
            String threadName,
            String projectId,
            String mojoId,
            Map<String, Object> keyValues,
            String messageTemplate,
            List<Object> messageArgs) {
        this(
                timestamp,
                level,
                message,
                loggerName,
                throwable,
                sourceClassName,
                sourceMethodName,
                threadId,
                sequenceNumber,
                threadName,
                projectId,
                mojoId,
                null,
                keyValues,
                messageTemplate,
                messageArgs);
    }

    @SuppressWarnings("checkstyle:ParameterNumber")
    public DefaultLogEvent(
            Instant timestamp,
            LogLevel level,
            String message,
            String loggerName,
            Throwable throwable,
            String sourceClassName,
            String sourceMethodName,
            long threadId,
            long sequenceNumber,
            String threadName,
            String projectId,
            String mojoId,
            String pluginId,
            Map<String, Object> keyValues,
            String messageTemplate,
            List<Object> messageArgs) {
        this.timestamp = timestamp;
        this.level = level;
        this.message = message;
        this.loggerName = loggerName;
        this.throwable = throwable;
        this.sourceClassName = sourceClassName;
        this.sourceMethodName = sourceMethodName;
        this.threadId = threadId;
        this.sequenceNumber = sequenceNumber;
        this.threadName = threadName;
        this.projectId = projectId;
        this.mojoId = mojoId;
        this.pluginId = pluginId;
        this.keyValues = keyValues != null ? Map.copyOf(keyValues) : Map.of();
        this.messageTemplate = messageTemplate;
        this.messageArgs = messageArgs != null ? messageArgs.toArray() : null;
        this.renderedLine = null;
    }

    /**
     * Full constructor for SLF4J-sourced events that carry a pre-rendered console line.
     */
    @SuppressWarnings("checkstyle:ParameterNumber")
    public DefaultLogEvent(
            Instant timestamp,
            LogLevel level,
            String message,
            String loggerName,
            Throwable throwable,
            String sourceClassName,
            String sourceMethodName,
            long threadId,
            long sequenceNumber,
            String threadName,
            String projectId,
            String mojoId,
            String pluginId,
            Map<String, Object> keyValues,
            String messageTemplate,
            List<Object> messageArgs,
            String renderedLine) {
        this.timestamp = timestamp;
        this.level = level;
        this.message = message;
        this.loggerName = loggerName;
        this.throwable = throwable;
        this.sourceClassName = sourceClassName;
        this.sourceMethodName = sourceMethodName;
        this.threadId = threadId;
        this.sequenceNumber = sequenceNumber;
        this.threadName = threadName;
        this.projectId = projectId;
        this.mojoId = mojoId;
        this.pluginId = pluginId;
        this.keyValues = keyValues != null ? Map.copyOf(keyValues) : Map.of();
        this.messageTemplate = messageTemplate;
        this.messageArgs = messageArgs != null ? messageArgs.toArray() : null;
        this.renderedLine = renderedLine;
    }

    /**
     * Constructor accepting message arguments as an array, avoiding the
     * {@code List ��� toArray()} conversion overhead on the logging hot path.
     */
    @SuppressWarnings("checkstyle:ParameterNumber")
    public DefaultLogEvent(
            Instant timestamp,
            LogLevel level,
            String message,
            String loggerName,
            Throwable throwable,
            String sourceClassName,
            String sourceMethodName,
            long threadId,
            long sequenceNumber,
            String threadName,
            String projectId,
            String mojoId,
            String pluginId,
            Map<String, Object> keyValues,
            String messageTemplate,
            Object[] messageArgs) {
        this.timestamp = timestamp;
        this.level = level;
        this.message = message;
        this.loggerName = loggerName;
        this.throwable = throwable;
        this.sourceClassName = sourceClassName;
        this.sourceMethodName = sourceMethodName;
        this.threadId = threadId;
        this.sequenceNumber = sequenceNumber;
        this.threadName = threadName;
        this.projectId = projectId;
        this.mojoId = mojoId;
        this.pluginId = pluginId;
        this.keyValues = keyValues != null ? Map.copyOf(keyValues) : Map.of();
        this.messageTemplate = messageTemplate;
        this.messageArgs = messageArgs != null ? messageArgs.clone() : null;
        this.renderedLine = null;
    }

    /**
     * Convenience constructor for events without structured data.
     */
    @SuppressWarnings("checkstyle:ParameterNumber")
    public DefaultLogEvent(
            Instant timestamp,
            LogLevel level,
            String message,
            String loggerName,
            Throwable throwable,
            String sourceClassName,
            String sourceMethodName,
            long threadId,
            long sequenceNumber,
            String threadName,
            String projectId,
            String mojoId) {
        this(
                timestamp,
                level,
                message,
                loggerName,
                throwable,
                sourceClassName,
                sourceMethodName,
                threadId,
                sequenceNumber,
                threadName,
                projectId,
                mojoId,
                Map.of(),
                null,
                (List<Object>) null);
    }

    /**
     * Convenience constructor for SLF4J events (no source metadata).
     */
    public DefaultLogEvent(Instant timestamp, LogLevel level, String message, String loggerName, Throwable throwable) {
        this(timestamp, level, message, loggerName, throwable, null, null, -1, -1, null, null, null);
    }

    @Override
    public Instant timestamp() {
        return timestamp;
    }

    @Override
    public LogLevel level() {
        return level;
    }

    @Override
    public String message() {
        if (message != null) {
            return message;
        }
        String m = formattedMessage;
        if (m == null) {
            m = formatMessage(messageTemplate, messageArgs);
            formattedMessage = m;
        }
        return m;
    }

    @Override
    public String loggerName() {
        return loggerName;
    }

    @Override
    public Throwable throwable() {
        return throwable;
    }

    @Override
    public String sourceClassName() {
        return sourceClassName;
    }

    @Override
    public String sourceMethodName() {
        return sourceMethodName;
    }

    @Override
    public long threadId() {
        return threadId;
    }

    @Override
    public long sequenceNumber() {
        return sequenceNumber;
    }

    @Override
    public String threadName() {
        return threadName;
    }

    @Override
    public String projectId() {
        return projectId;
    }

    @Override
    public String mojoId() {
        return mojoId;
    }

    @Override
    public String pluginId() {
        return pluginId;
    }

    @Override
    public Map<String, Object> keyValues() {
        return keyValues;
    }

    @Override
    public String messageTemplate() {
        return messageTemplate;
    }

    @Override
    public List<Object> messageArgs() {
        Object[] args = this.messageArgs;
        if (args == null) {
            return null;
        }
        List<Object> list = this.messageArgsList;
        if (list == null) {
            list = Collections.unmodifiableList(Arrays.asList(args));
            this.messageArgsList = list;
        }
        return list;
    }

    @Override
    public String renderedLine() {
        String r = renderedLine;
        if (r == null) {
            r = LoggerManager.get().formatLine(this);
            renderedLine = r;
        }
        return r;
    }

    static String formatMessage(String template, Object[] args) {
        if (template == null) {
            return "";
        }
        if (args == null || args.length == 0) {
            return template;
        }
        StringBuilder sb = new StringBuilder(template.length() + 32);
        int len = template.length();
        int i = 0;
        while (i < len) {
            char c = template.charAt(i);
            if (c == '{' && i + 1 < len) {
                int j = i + 1;
                int idx = 0;
                boolean hasDigits = false;
                while (j < len && template.charAt(j) >= '0' && template.charAt(j) <= '9') {
                    idx = idx * 10 + (template.charAt(j) - '0');
                    j++;
                    hasDigits = true;
                }
                if (hasDigits && j < len && template.charAt(j) == '}') {
                    if (idx < args.length) {
                        sb.append(args[idx]);
                    } else {
                        sb.append(template, i, j + 1);
                    }
                    i = j + 1;
                    continue;
                }
            }
            sb.append(c);
            i++;
        }
        return sb.toString();
    }
}