001/*
002 * Copyright 2023 the original author or authors.
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * https://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package de.cuioss.tools.logging;
017
018import static de.cuioss.tools.reflect.MoreReflection.findCaller;
019
020import java.util.Set;
021import java.util.function.Supplier;
022
023import de.cuioss.tools.collect.CollectionLiterals;
024import lombok.experimental.UtilityClass;
025
026/**
027 * Class provide factory method for CuiLogger instance
028 */
029@UtilityClass
030public class CuiLoggerFactory {
031
032    static final Set<String> MARKER_CLASS_NAMES = CollectionLiterals.immutableSet(CuiLogger.class.getName(),
033            CuiLoggerFactory.class.getName());
034
035    private static final Supplier<IllegalStateException> ILLEGAL_STATE_EXCEPTION_SUPPLIER = () -> new IllegalStateException(
036            "Unable to detect caller class name. Make sure '" + MARKER_CLASS_NAMES + "' was used for creation.");
037
038    /**
039     * Automatic determine the caller class.
040     *
041     * @return {@link CuiLogger}
042     * @throws IllegalStateException if caller couldn't be detected
043     */
044    public static CuiLogger getLogger() {
045        return getLogger(findCaller(MARKER_CLASS_NAMES).orElseThrow(ILLEGAL_STATE_EXCEPTION_SUPPLIER));
046    }
047
048    /**
049     * Create logger and use the hand-over class name as logger name
050     *
051     * @param className must not be null
052     * @return {@link CuiLogger}
053     */
054    public static CuiLogger getLogger(final String className) {
055        return new CuiLogger(className);
056    }
057
058    /**
059     * Create logger and use the hand-over class name as logger name
060     *
061     * @param clazz must not be null
062     * @return {@link CuiLogger}
063     */
064    public static CuiLogger getLogger(final Class<?> clazz) {
065        return new CuiLogger(clazz);
066    }
067
068}