View Javadoc
1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v2.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.kryo;
15  
16  import ch.qos.logback.classic.spi.ILoggingEvent;
17  import ch.qos.logback.core.encoder.EncoderBase;
18  import com.esotericsoftware.kryo.kryo5.Kryo;
19  import com.esotericsoftware.kryo.kryo5.io.Output;
20  
21  import static ch.qos.logback.classic.kryo.KryoClassicConstants.*;
22  
23  public class KryoEncoder extends EncoderBase<ILoggingEvent> {
24  
25  
26      public enum SerializerType {
27          Vanilla,
28          Custom
29      };
30  
31      static int MAX_BUFFER_SIZE = 1024 * 64;
32  
33      Kryo kryo;
34      byte[] buffer = new byte[MAX_BUFFER_SIZE];
35      Output output = new Output(buffer);
36  
37      SerializerType serializerType = SerializerType.Custom;
38      byte streamVersion = STREAM_VERSION_5;
39      /** True once {@link #setStreamVersion(int)} was called, e.g. from configuration. */
40      boolean streamVersionExplicitlySet = false;
41  
42      int eventsInEpoch;
43      int maxEventsBeforeReset = DEFAULT_MAX_EVENTS_BEFORE_RESET;
44  
45      @Override
46      public void start() {
47          // Vanilla streams are unframed and always carry version 0
48          if (serializerType == SerializerType.Vanilla && streamVersion != STREAM_VERSION_0) {
49              // the default stream version applies to Custom; warn only about an explicit setting
50              if (streamVersionExplicitlySet) {
51                  addWarn("Stream version " + streamVersion + " is not applicable to the Vanilla serializer type. Using stream version "
52                          + STREAM_VERSION_0 + " instead.");
53              }
54              this.streamVersion = STREAM_VERSION_0;
55          }
56          this.kryo = makeFreshKryo();
57          if(kryo == null) {
58              addError("Kryo serializer is null");
59              return;
60          }
61          this.eventsInEpoch = 0;
62          super.start();
63      }
64  
65      @Override
66      public boolean isStateful() {
67          return true;
68      }
69  
70      boolean isFramed() {
71          return KryoClassicConstants.isFramed(streamVersion);
72      }
73  
74      public int getMaxEventsBeforeReset() {
75          return maxEventsBeforeReset;
76      }
77  
78      public void setMaxEventsBeforeReset(int maxEventsBeforeReset) {
79          if (maxEventsBeforeReset < 1) {
80              throw new IllegalArgumentException("maxEventsBeforeReset must be >= 1");
81          }
82          this.maxEventsBeforeReset = maxEventsBeforeReset;
83      }
84  
85      Kryo makeFreshKryo() {
86          return KryoBuilder.build(serializerType, streamVersion);
87      }
88  
89      public void setSerializerType(SerializerType serializerType) {
90          this.serializerType = serializerType;
91      }
92  
93      public SerializerType getSerializerType() {
94          return serializerType;
95      }
96  
97      /**
98       * Stream format version written into the header: {@link KryoClassicConstants#STREAM_VERSION_0}
99       * for Vanilla, {@link KryoClassicConstants#STREAM_VERSION_5} for Custom
100      * ({@link LoggingEventKryoVOSerializerV5}, framed with {@link StreamFrameV5}).
101      */
102     public void setStreamVersion(int streamVersion) {
103         this.streamVersion = (byte) streamVersion;
104         this.streamVersionExplicitlySet = true;
105     }
106 
107     public byte getStreamVersion() {
108         return streamVersion;
109     }
110 
111     /**
112      * Fixed stream preamble: magic (4) + version (1) + flags (1).
113      * Written once at the start of the stream by the appender.
114      */
115     @Override
116     public byte[] headerBytes() {
117         byte flags = (serializerType == SerializerType.Custom) ? FLAG_CUSTOM_SERIALIZER : 0;
118         return new byte[] {
119                 STREAM_MAGIC[0], STREAM_MAGIC[1], STREAM_MAGIC[2], STREAM_MAGIC[3],
120                 streamVersion,
121                 flags
122         };
123     }
124 
125     @Override
126     synchronized public byte[] encode(ILoggingEvent loggingEvent) {
127         LoggingEventKryoVO loggerEventKryoVO = new LoggingEventKryoVO(loggingEvent);
128         if (!isFramed()) {
129             output.setPosition(0);
130             kryo.writeObject(output, loggerEventKryoVO);
131             output.flush();
132             return copyOf(buffer, 0, output.position());
133         }
134 
135         int reserved = StreamFrameV5.MAX_PREFIX;
136         output.setPosition(reserved);
137         kryo.writeObject(output, loggerEventKryoVO);
138         output.flush();
139         int payloadLen = output.position() - reserved;
140         int prefixLen = StreamFrameV5.writeEventPrefix(buffer, reserved, payloadLen);
141         int start = reserved - prefixLen;
142         int framedLen = prefixLen + payloadLen;
143         eventsInEpoch++;
144         if (eventsInEpoch < maxEventsBeforeReset) {
145             return copyOf(buffer, start, framedLen);
146         }
147         byte[] close = StreamFrameV5.closeCode();
148         byte[] header = headerBytes();
149         byte[] out = new byte[framedLen + close.length + header.length];
150         System.arraycopy(buffer, start, out, 0, framedLen);
151         System.arraycopy(close, 0, out, framedLen, close.length);
152         System.arraycopy(header, 0, out, framedLen + close.length, header.length);
153         resetEpoch();
154         return out;
155     }
156 
157     private static byte[] copyOf(byte[] src, int off, int len) {
158         byte[] out = new byte[len];
159         System.arraycopy(src, off, out, 0, len);
160         return out;
161     }
162 
163     @Override
164     synchronized public byte[] footerBytes() {
165         if (isFramed() && eventsInEpoch > 0) {
166             resetEpoch();
167             return StreamFrameV5.closeCode();
168         }
169         resetEpoch();
170         return new byte[0];
171     }
172 
173     private void resetEpoch() {
174         eventsInEpoch = 0;
175         kryo = makeFreshKryo();
176         if (kryo == null) {
177             addError("Kryo serializer is null");
178         }
179     }
180 }