View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, 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  package ch.qos.logback.classic.sift;
15  
16  import ch.qos.logback.classic.Level;
17  import ch.qos.logback.classic.Logger;
18  import ch.qos.logback.classic.LoggerContext;
19  import ch.qos.logback.classic.spi.LoggingEvent;
20  import ch.qos.logback.classic.util.LogbackMDCAdapter;
21  import ch.qos.logback.core.testUtil.RandomUtil;
22  import org.junit.jupiter.api.AfterEach;
23  import org.junit.jupiter.api.BeforeEach;
24  import org.junit.jupiter.api.Test;
25  import org.slf4j.MDC;
26  
27  import java.util.HashMap;
28  
29  import static org.junit.jupiter.api.Assertions.assertEquals;
30  import static org.junit.jupiter.api.Assertions.assertTrue;
31  
32  /**
33   * @author Ceki Gülcü
34   */
35  public class MDCBasedDiscriminatorTest {
36  
37      static String DEFAULT_VAL = "DEFAULT_VAL";
38  
39      MDCBasedDiscriminator discriminator = new MDCBasedDiscriminator();
40      LoggerContext loggerContext = new LoggerContext();
41      LogbackMDCAdapter logbackMDCAdapter = new LogbackMDCAdapter();
42      Logger logger = loggerContext.getLogger(this.getClass());
43  
44      int diff = RandomUtil.getPositiveInt();
45      String key = "MDCBasedDiscriminatorTest_key" + diff;
46      String value = "MDCBasedDiscriminatorTest_val" + diff;
47      LoggingEvent event;
48  
49      @BeforeEach
50      public void setUp() {
51          loggerContext.setMDCAdapter(logbackMDCAdapter);
52          discriminator.setContext(loggerContext);
53          discriminator.setKey(key);
54          discriminator.setDefaultValue(DEFAULT_VAL);
55          discriminator.start();
56          assertTrue(discriminator.isStarted());
57      }
58  
59      @AfterEach
60      public void teaDown() {
61          MDC.clear();
62      }
63  
64      @Test
65      public void smoke() {
66          logbackMDCAdapter.put(key, value);
67          event = new LoggingEvent("a", logger, Level.DEBUG, "", null, null);
68  
69          String discriminatorValue = discriminator.getDiscriminatingValue(event);
70          assertEquals(value, discriminatorValue);
71      }
72  
73      @Test
74      public void nullMDC() {
75          event = new LoggingEvent("a", logger, Level.DEBUG, "", null, null);
76          assertEquals(new HashMap<String, String>(), event.getMDCPropertyMap());
77          String discriminatorValue = discriminator.getDiscriminatingValue(event);
78          assertEquals(DEFAULT_VAL, discriminatorValue);
79      }
80  }