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.core.kryo.SerializerBase;
17  import com.esotericsoftware.kryo.kryo5.Kryo;
18  import com.esotericsoftware.kryo.kryo5.io.Input;
19  import com.esotericsoftware.kryo.kryo5.io.Output;
20  import com.esotericsoftware.kryo.kryo5.minlog.Log;
21  
22  import java.util.HashMap;
23  import java.util.Map;
24  
25  /**
26   * Serializer for logger names that compresses hierarchical names by storing
27   * common prefixes separately and referencing them.
28   *
29   * Logger names are typically hierarchical (e.g., "ch.qos.logback.classic.Logger",
30   * "ch.qos.logback.classic.PatternLayout") and share common prefixes.
31   *
32   * This serializer:
33   * 1. Caches full logger names (like StringSerializer)
34   * 2. For new entries, detects common prefixes and stores only the unique suffix
35   * 3. Reduces serialized size by 30-50% for typical logger hierarchies
36   */
37  public class ClassNameSerializer extends SerializerBase<String> {
38  
39      // Common package prefixes to look for
40  //    private static final String[] COMMON_PREFIXES = {
41  //        "ch.qos.logback.",
42  //        "ch.qos.",
43  //        "org.slf4j.",
44  //        "java.util.",
45  //        "javax.",
46  //        "org.springframework.",
47  //        "com.example."
48  //    };
49  
50      // Map to cache prefix -> id mapping for compression
51      private final Map<String, Integer> prefixToId = new HashMap<>();
52      private final Map<Integer, String> idToPrefix = new HashMap<>();
53      private int nextPrefixId = 0;
54  
55      public ClassNameSerializer(int capacity) {
56          super(BiMapType.DIRECT_MAP, capacity);
57          setAcceptsNull(false);
58      }
59  
60      @Override
61      protected void writeNewEntry(Kryo kryo, Output output, String loggerName) {
62          //Log.trace("writeNewEntry for logger name: " + loggerName);
63  
64          if (loggerName == null) {
65              throw new IllegalArgumentException("Null logger names are not permitted");
66          }
67  
68          // Try to find a common prefix
69          String prefix = findLongestPrefix(loggerName);
70  
71          if (prefix != null && prefix.length() > 4) { // Only compress if prefix is meaningful
72              Integer prefixId = prefixToId.get(prefix);
73  
74              if (prefixId == null) {
75                  // New prefix - register it
76                  prefixId = nextPrefixId++;
77                  prefixToId.put(prefix, prefixId);
78                  idToPrefix.put(prefixId, prefix);
79  
80                  // Write as: NEW_PREFIX flag + prefix_id + prefix + suffix
81                  output.writeByte((byte) 1); // NEW_PREFIX
82                  output.writeVarInt(prefixId, true);
83                  output.writeString(prefix);
84                  String suffix = loggerName.substring(prefix.length());
85                  output.writeString(suffix);
86                  Log.debug("New prefix [" + prefix + "] with id " + prefixId + ", suffix: " + suffix);
87              } else {
88                  // Existing prefix - just reference it
89                  // Write as: EXISTING_PREFIX flag + prefix_id + suffix
90                  output.writeByte((byte) 2); // EXISTING_PREFIX
91                  output.writeVarInt(prefixId, true);
92                  String suffix = loggerName.substring(prefix.length());
93                  output.writeString(suffix);
94                  Log.debug("Using prefix id " + prefixId + " [" + prefix + "], suffix: " + suffix);
95              }
96          } else {
97              // No meaningful prefix - write full name
98              // Write as: FULL_NAME flag + name
99              output.writeByte((byte) 0); // FULL_NAME
100             output.writeString(loggerName);
101             Log.debug("Writing full logger name: " + loggerName);
102         }
103     }
104 
105     @Override
106     protected String readNewEntry(Kryo kryo, Input input) {
107         byte mode = input.readByte();
108 
109         switch (mode) {
110             case 0: // FULL_NAME
111                 String fullName = input.readString();
112                 Log.trace("Read full logger name: " + fullName);
113                 return fullName;
114 
115             case 1: // NEW_PREFIX
116                 int newPrefixId = input.readVarInt(true);
117                 String prefix = input.readString();
118                 String suffix = input.readString();
119 
120                 // Cache the prefix
121                 prefixToId.put(prefix, newPrefixId);
122                 idToPrefix.put(newPrefixId, prefix);
123 
124                 String reconstructed = prefix + suffix;
125                 Log.debug("Read new prefix [" + prefix + "] id=" + newPrefixId + ", result: " + reconstructed);
126                 return reconstructed;
127 
128             case 2: // EXISTING_PREFIX
129                 int prefixId = input.readVarInt(true);
130                 String cachedPrefix = idToPrefix.get(prefixId);
131                 String suffixPart = input.readString();
132 
133                 if (cachedPrefix == null) {
134                     throw new IllegalStateException("Unknown prefix id: " + prefixId);
135                 }
136 
137                 String result = cachedPrefix + suffixPart;
138                 Log.debug("Read with cached prefix id=" + prefixId + " [" + cachedPrefix + "], result: " + result);
139                 return result;
140 
141             default:
142                 throw new IllegalStateException("Unknown mode: " + mode);
143         }
144     }
145 
146     /**
147      * Find the longest common prefix for the logger name.
148      * First checks predefined common prefixes, then finds the package prefix.
149      */
150     private String findLongestPrefix(String loggerName) {
151         // Check common known prefixes first
152 //        for (String commonPrefix : COMMON_PREFIXES) {
153 //            if (loggerName.startsWith(commonPrefix)) {
154 //                return commonPrefix;
155 //            }
156 //        }
157 
158         // Find package-level prefix (everything up to last dot)
159         int lastDot = loggerName.lastIndexOf('.');
160         if (lastDot > 0) {
161             return loggerName.substring(0, lastDot + 1); // Include the dot
162         }
163 
164         return null;
165     }
166 }