hazelcast-master/hazelcast/src/test/java/com/hazelcast/logging/Log4jTrackingAppender.java
/*
 * Copyright (c) 2008-2023, Hazelcast, Inc. All Rights Reserved.
 *
 * Licensed 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 com.hazelcast.logging;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

import static org.assertj.core.api.Assertions.assertThat;

class Log4jTrackingAppender extends AppenderSkeleton {

    private int hits;
    private final String trackedLoggerName;

    Log4jTrackingAppender(String trackedLoggerName) {
        this.trackedLoggerName = trackedLoggerName;
        this.name = trackedLoggerName + "TestAppender";
    }

    static Log4jTrackingAppender registerTrackingAppender(String loggerName) {
        Log4jTrackingAppender testAppender = new Log4jTrackingAppender(loggerName);
        org.apache.log4j.Logger.getLogger(loggerName).addAppender(testAppender);
        return testAppender;
    }

    @Override
    public void close() {
        // do nothing
    }

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

    @Override
    protected void append(LoggingEvent event) {
        if (trackedLoggerName.equals(event.getLoggerName())) {
            hits++;
        }
    }

    void assertNumberOfLoggedEvents(int expected) {
        assertThat(hits).as("Expected %d log events but got %d", expected, hits).isEqualTo(expected);
    }

    void assertNoLoggedEvents() {
        assertNumberOfLoggedEvents(0);
    }
}
