View Javadoc
1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2023, 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 v1.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  
15  package ch.qos.logback.classic.jsonTest;
16  
17  import ch.qos.logback.classic.encoder.JsonEncoder;
18  import ch.qos.logback.classic.spi.LoggerContextVO;
19  import com.fasterxml.jackson.core.JacksonException;
20  import com.fasterxml.jackson.core.JsonParser;
21  import com.fasterxml.jackson.databind.DeserializationContext;
22  import com.fasterxml.jackson.databind.JsonNode;
23  import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
24  import org.slf4j.event.KeyValuePair;
25  
26  import java.io.IOException;
27  import java.util.HashMap;
28  import java.util.Iterator;
29  import java.util.Map;
30  
31  public class LoggerContextVODeserializer  extends StdDeserializer<LoggerContextVO> {
32  
33      public  LoggerContextVODeserializer() {
34          this(null);
35      }
36  
37      public  LoggerContextVODeserializer(Class<?> vc) {
38          super(vc);
39      }
40  
41      @Override
42      public LoggerContextVO deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
43              throws IOException, JacksonException {
44  
45          JsonNode node = jsonParser.getCodec().readTree(jsonParser);
46          if(node.isObject()) {
47              JsonNode nameNode = node.get(JsonEncoder.NAME_ATTR_NAME);
48              String name = nameNode.asText();
49              JsonNode bdayNode = node.get(JsonEncoder.BIRTHDATE_ATTR_NAME);
50              long birthday = bdayNode.asLong();
51  
52              JsonNode propertiesNode = node.get(JsonEncoder.CONTEXT_PROPERTIES_ATTR_NAME);
53              Map<String, String> propertiesMap = new HashMap<>();
54              Iterator<Map.Entry<String, JsonNode>> it = propertiesNode.fields();
55              while(it.hasNext()) {
56                  Map.Entry<String, JsonNode> entry = it.next();
57                  String key = entry.getKey();
58                  String value = entry.getValue().asText();
59                  propertiesMap.put(key, value);
60              }
61              return  new LoggerContextVO(name, propertiesMap, birthday);
62          }
63          return null;
64      }
65  }