001/*
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v2.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.kryo;
015
016import ch.qos.logback.classic.spi.LoggerContextVO;
017import ch.qos.logback.classic.spi.ThrowableProxyVO;
018import ch.qos.logback.core.kryo.SerializerBase;
019import ch.qos.logback.core.kryo.SerializerBase.BiMapType;
020import com.esotericsoftware.kryo.kryo5.Kryo;
021import com.esotericsoftware.kryo.kryo5.Serializer;
022import com.esotericsoftware.kryo.kryo5.io.Input;
023import com.esotericsoftware.kryo.kryo5.io.Output;
024import com.esotericsoftware.kryo.kryo5.serializers.CollectionSerializer;
025import org.slf4j.Marker;
026import org.slf4j.event.KeyValuePair;
027
028import java.util.ArrayList;
029import java.util.List;
030import java.util.Map;
031
032/**
033 * Stream version 5 event serializer.
034 *
035 * <p>Logger name, level and thread name are followed by a 1-byte presence bitmap for
036 * message, arguments, markers, key-value pairs, MDC, throwable and {@code callerData}
037 * (usually absent). Message may be null (fluent {@code .log()} with no message).
038 * Present fields are written with {@code writeObject} (no per-field null byte).
039 * Timestamp and nanoseconds are one {@link LongDeltaSerializer} field:
040 * {@code (epochSecond << 30) | nanos}. Caller data follows throwable when present.
041 *
042 * <p>Long unique strings (message, string arguments, KVP string values and MDC values)
043 * share one {@link MultiEventCompressedStringSerializer} so there is a single deflate
044 * stream. Short repeating strings (thread name, MDC keys, KVP keys) use
045 * {@link BasicStringSerializer} and the id cache.
046 *
047 * <p>Logger names and stack-frame class names (caller data and throwable frames) use
048 * {@link BasicStringSerializer}. Each of the three has its own instance.
049 *
050 * <p>Selected when the stream header version is
051 * {@link KryoClassicConstants#STREAM_VERSION_5}.
052 */
053public class LoggingEventKryoVOSerializerV5 extends Serializer<LoggingEventKryoVO> implements FieldByteAccumulatorAware {
054
055    static final int PRESENT_MESSAGE = 1 << 0;
056    static final int PRESENT_ARGUMENTS = 1 << 1;
057    static final int PRESENT_MARKERS = 1 << 2;
058    static final int PRESENT_KVP = 1 << 3;
059    static final int PRESENT_MDC = 1 << 4;
060    static final int PRESENT_THROWABLE = 1 << 5;
061    static final int PRESENT_CALLER_DATA = 1 << 6;
062
063    /** Bits of {@code Instant.getNano()} in the packed epoch field. {@code 2^30 > 10^9-1}. */
064    static final int NANO_BITS = 30;
065    static final int NANO_MASK = 0x3FFFFFFF;
066
067    protected final FieldByteAccumulator fieldByteAccumulator = new FieldByteAccumulator();
068
069    /**
070     * Shared by message, string arguments, KVP string values and MDC values.
071     */
072    protected final MultiEventCompressedStringSerializer longUniqueStrings = new MultiEventCompressedStringSerializer(1024);
073
074    protected final LoggerContextVOSerializer loggerContextVOSerializer = new LoggerContextVOSerializer(1024);
075    /** Logger names are cached whole; no package-prefix table. */
076    protected final SerializerBase<String> classNameSerializer = new BasicStringSerializer(BiMapType.DIRECT_MAP, 2048);
077    protected final Serializer<String> threadNameSerializer = new BasicStringSerializer(1024);
078    protected final SerializerBase<String> messageSerializer = longUniqueStrings;
079    protected final MDCPropertyMapSerializer mdcPropertyMapSerializer = new MDCPropertyMapSerializerV5(1024, longUniqueStrings);
080    /** Frame class names use their own {@link BasicStringSerializer}. */
081    protected final Serializer<ThrowableProxyVO> throwableProxyVOSerializer = new ThrowableProxyVOSerializerV5(1024,
082            new StackTraceElementProxySerializerV5(1024, new BasicStringSerializer(BiMapType.DIRECT_MAP, 1024)));
083    protected final LongDeltaSerializer timestampDeltaSerializer = new LongDeltaSerializer();
084    protected final LongDeltaSerializer sequenceNumberDeltaSerializer = new LongDeltaSerializer();
085    protected final ArgumentArraySerializerV5 argumentArraySerializerV5 = new ArgumentArraySerializerV5(longUniqueStrings);
086    protected final CollectionSerializer<ArrayList<KeyValuePair>> kvpCollectionSerializer = new KeyValuePairCollectionSerializerV5(
087            new KeyValuePairSerializerV5(new BasicStringSerializer(1024), longUniqueStrings));
088    /** Caller-data frames. Class names have their own {@link BasicStringSerializer}. */
089    protected final Serializer<StackTraceElement> stackTraceElementSerializer =
090            new StackTraceElementSerializer(1024, new BasicStringSerializer(BiMapType.DIRECT_MAP, 1024));
091
092    @Override
093    public void write(Kryo kryo, Output output, LoggingEventKryoVO event) {
094        LoggerContextVO loggerContextVO = event.getLoggerContextVO();
095        kryo.writeObject(output, loggerContextVO, loggerContextVOSerializer);
096        kryo.writeObject(output, event.getLoggerName(), classNameSerializer);
097        output.writeByte(LevelSerializer.levelIntToByte(event.levelInt));
098        kryo.writeObject(output, event.getThreadName(), threadNameSerializer);
099
100        String message = event.getMessage();
101        Object[] argumentArray = event.getArgumentArray();
102        List<Marker> markerList = event.getMarkerList();
103        List<KeyValuePair> keyValuePairs = event.getKeyValuePairs();
104        Map<String, String> mdcPropertyMap = event.getMDCPropertyMap();
105        ThrowableProxyVO throwableProxy = (ThrowableProxyVO) event.getThrowableProxy();
106        StackTraceElement[] callerData = event.hasCallerData() ? event.getCallerData() : null;
107
108        int presence = 0;
109        if (message != null) {
110            presence |= PRESENT_MESSAGE;
111        }
112        if (argumentArray != null) {
113            presence |= PRESENT_ARGUMENTS;
114        }
115        if (markerList != null) {
116            presence |= PRESENT_MARKERS;
117        }
118        if (keyValuePairs != null) {
119            presence |= PRESENT_KVP;
120        }
121        if (mdcPropertyMap != null) {
122            presence |= PRESENT_MDC;
123        }
124        if (throwableProxy != null) {
125            presence |= PRESENT_THROWABLE;
126        }
127        if (callerData != null) {
128            presence |= PRESENT_CALLER_DATA;
129        }
130        output.writeByte(presence);
131
132        if ((presence & PRESENT_MESSAGE) != 0) {
133            kryo.writeObject(output, message, messageSerializer);
134        }
135        if ((presence & PRESENT_ARGUMENTS) != 0) {
136            kryo.writeObject(output, argumentArray, argumentArraySerializerV5);
137        }
138        if ((presence & PRESENT_MARKERS) != 0) {
139            kryo.writeObject(output, markerList, kryo.getSerializer(ArrayList.class));
140        }
141        if ((presence & PRESENT_KVP) != 0) {
142            kryo.writeObject(output, keyValuePairs, kvpCollectionSerializer);
143        }
144        if ((presence & PRESENT_MDC) != 0) {
145            kryo.writeObject(output, mdcPropertyMap, mdcPropertyMapSerializer);
146        }
147
148        timestampDeltaSerializer.writeLong(output, packEpoch(event.getTimeStamp(), event.getNanoseconds()));
149        sequenceNumberDeltaSerializer.writeLong(output, event.getSequenceNumber());
150
151        if ((presence & PRESENT_THROWABLE) != 0) {
152            kryo.writeObject(output, throwableProxy, throwableProxyVOSerializer);
153        }
154        if ((presence & PRESENT_CALLER_DATA) != 0) {
155            writeCallerData(kryo, output, callerData);
156        }
157    }
158
159    @Override
160    public LoggingEventKryoVO read(Kryo kryo, Input input, Class<? extends LoggingEventKryoVO> type) {
161        LoggerContextVO loggerContextVO = fieldByteAccumulator.read(input, "loggerContext",
162                () -> kryo.readObject(input, LoggerContextVO.class, loggerContextVOSerializer));
163        String loggerName = fieldByteAccumulator.read(input, "loggerName",
164                () -> kryo.readObject(input, String.class, classNameSerializer));
165        int levelInt = fieldByteAccumulator.read(input, "level",
166                () -> LevelSerializer.byteToLevelInt(input.readByte()));
167        String threadName = fieldByteAccumulator.read(input, "threadName",
168                () -> kryo.readObject(input, String.class, threadNameSerializer));
169
170        int presence = fieldByteAccumulator.read(input, "presence",
171                () -> input.readByte() & 0xFF);
172
173        String message = ((presence & PRESENT_MESSAGE) != 0)
174                ? fieldByteAccumulator.read(input, "message",
175                () -> kryo.readObject(input, String.class, messageSerializer))
176                : null;
177        Object[] argArray = ((presence & PRESENT_ARGUMENTS) != 0)
178                ? fieldByteAccumulator.read(input, "argumentArray",
179                () -> kryo.readObject(input, Object[].class, argumentArraySerializerV5))
180                : null;
181        List<Marker> markerList = ((presence & PRESENT_MARKERS) != 0)
182                ? fieldByteAccumulator.read(input, "markers",
183                () -> kryo.readObject(input, ArrayList.class))
184                : null;
185        List<KeyValuePair> keyValuePairs = ((presence & PRESENT_KVP) != 0)
186                ? fieldByteAccumulator.read(input, "keyValuePairs",
187                () -> kryo.readObject(input, ArrayList.class, kvpCollectionSerializer))
188                : null;
189        Map<String, String> mdcPropertyMap = ((presence & PRESENT_MDC) != 0)
190                ? fieldByteAccumulator.read(input, "mdc",
191                () -> kryo.readObject(input, Map.class, mdcPropertyMapSerializer))
192                : null;
193
194        long packed = fieldByteAccumulator.readLong(input, "timestamp",
195                () -> timestampDeltaSerializer.readLong(input));
196        long timestamp = unpackTimestamp(packed);
197        int nanoseconds = unpackNanoseconds(packed);
198        long sequenceNumber = fieldByteAccumulator.readLong(input, "sequenceNumber",
199                () -> sequenceNumberDeltaSerializer.readLong(input));
200        ThrowableProxyVO throwableProxy = ((presence & PRESENT_THROWABLE) != 0)
201                ? fieldByteAccumulator.read(input, "throwable",
202                () -> kryo.readObject(input, ThrowableProxyVO.class, throwableProxyVOSerializer))
203                : null;
204        StackTraceElement[] callerData = ((presence & PRESENT_CALLER_DATA) != 0)
205                ? fieldByteAccumulator.read(input, "callerData",
206                () -> readCallerData(kryo, input))
207                : null;
208
209        LoggingEventKryoVO.Builder eventBuilder = new LoggingEventKryoVO.Builder();
210        eventBuilder.withLoggerContextVO(loggerContextVO);
211        eventBuilder.withLoggerName(loggerName);
212        eventBuilder.withLevelInt(levelInt);
213        eventBuilder.withThreadName(threadName);
214        eventBuilder.withMessage(message);
215        eventBuilder.withArgumentArray(argArray);
216        eventBuilder.withMarkerList(markerList);
217        eventBuilder.withKeyValuePairList(keyValuePairs);
218        eventBuilder.withMdcPropertyMap(mdcPropertyMap);
219        eventBuilder.withTimestamp(timestamp);
220        eventBuilder.withNanoseconds(nanoseconds);
221        eventBuilder.withSequenceNumber(sequenceNumber);
222        eventBuilder.withThrowableProxy(throwableProxy);
223        eventBuilder.withCallerData(callerData);
224        return eventBuilder.build();
225    }
226
227    public void writeCallerData(Kryo kryo, Output output, StackTraceElement[] callerData) {
228        output.writeVarInt(callerData.length, true);
229        for (StackTraceElement ste : callerData) {
230            kryo.writeObject(output, ste, stackTraceElementSerializer);
231        }
232    }
233
234    public StackTraceElement[] readCallerData(Kryo kryo, Input input) {
235        int length = input.readVarInt(true);
236        StackTraceElement[] callerData = new StackTraceElement[length];
237        for (int i = 0; i < length; i++) {
238            callerData[i] = kryo.readObject(input, StackTraceElement.class, stackTraceElementSerializer);
239        }
240        return callerData;
241    }
242
243    /**
244     * Packs epoch-millisecond timestamp and nano-of-second. {@code timestamp / 1000}
245     * is {@link java.time.Instant#getEpochSecond()} for non-negative timestamps
246     * (these streams are post-1970).
247     */
248    static long packEpoch(long timestamp, int nanoseconds) {
249        long epochSecond = timestamp / 1000;
250        return (epochSecond << NANO_BITS) | (nanoseconds & NANO_MASK);
251    }
252
253    static long unpackTimestamp(long packed) {
254        long epochSecond = packed >>> NANO_BITS;
255        int nanoseconds = unpackNanoseconds(packed);
256        return epochSecond * 1000 + nanoseconds / 1_000_000;
257    }
258
259    static int unpackNanoseconds(long packed) {
260        return (int) (packed & NANO_MASK);
261    }
262
263    @Override
264    public FieldByteAccumulator getFieldByteAccumulator() {
265        return fieldByteAccumulator;
266    }
267}