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.string.MoreStrings.lenientFormat; 019import static de.cuioss.tools.string.MoreStrings.nullToEmpty; 020 021import java.util.function.Supplier; 022 023import lombok.Builder; 024import lombok.Getter; 025import lombok.NonNull; 026 027/** 028 * Represents a log-entry. Especially focuses on enforcing log-entry identifier, 029 * see {@link #getPrefix()} and {@link #getIdentifier()}. The template mechanism 030 * is the same as with {@link CuiLogger}, saying it accepts as well '%s' and 031 * '{}' as placeholder, even mixed. To simplify usage the prefix string will 032 * always be prepended on calling {@link #format(Object...)} 033 * 034 * @author Oliver Wolff 035 * 036 */ 037public class LogRecordModel implements LogRecord { 038 039 private static final String PREFIX_IDENTIFIER_TEMPLATE = "%s-%s"; 040 private static final String AFTER_PREFIX = ": "; 041 042 @Getter 043 @NonNull 044 private final String prefix; 045 046 @Getter 047 @NonNull 048 private final Integer identifier; 049 050 @Getter 051 @NonNull 052 private final String template; 053 054 /** Tiniest of optimization. Needs to be verified. */ 055 private String parsedMessageTemplate; 056 private String parsedIdentifier; 057 058 protected String getParsedMessageTemplate() { 059 if (null == parsedMessageTemplate) { 060 parsedMessageTemplate = CuiLogger.SLF4J_PATTERN.matcher(nullToEmpty(getTemplate())).replaceAll("%s"); 061 } 062 return parsedMessageTemplate; 063 } 064 065 @Override 066 public String format(Object... parameter) { 067 return new StringBuilder(resolveIdentifierString()).append(AFTER_PREFIX) 068 .append(lenientFormat(getParsedMessageTemplate(), parameter)).toString(); 069 } 070 071 @Override 072 public Supplier<String> supplier(Object... parameter) { 073 return () -> format(parameter); 074 } 075 076 @Override 077 public String resolveIdentifierString() { 078 if (null == parsedIdentifier) { 079 parsedIdentifier = String.format(PREFIX_IDENTIFIER_TEMPLATE, getPrefix(), getIdentifier()); 080 } 081 return parsedIdentifier; 082 } 083 084 @Builder 085 private LogRecordModel(@NonNull String prefix, @NonNull Integer identifier, @NonNull String template) { 086 this.prefix = prefix; 087 this.identifier = identifier; 088 this.template = template; 089 } 090 091}