// NDC.java -- // // NDC.java is part of the ElectricCommander server. // // Copyright (c) 2005-2009 Electric Cloud, Inc. // All rights reserved. // package com.electriccloud.log; import java.util.Deque; import java.util.LinkedList; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.slf4j.MDC; /** * Utility object that implements NDC using MDC. */ @SuppressWarnings({"UtilityClass", "StringContatenationInLoop"}) public class NDC { //~ Static fields/initializers --------------------------------------------- private static final ThreadLocal> s_stack = new ThreadLocal>() { @Override @SuppressWarnings({"RefusedBequest"}) protected Deque initialValue() { return new LinkedList(); } }; //~ Constructors ----------------------------------------------------------- private NDC() { } //~ Methods ---------------------------------------------------------------- public static void pop() { Deque stack = s_stack.get(); // Pop the stack if isn't already empty if (!stack.isEmpty()) { stack.pop(); } // Put the previous value in the MDC (null if the stack is now empty) MDC.put("NDC", stack.peek()); } @SuppressWarnings({"HardCodedStringLiteral"}) public static void push(@NonNls @NotNull String format, Object... args) { Deque stack = s_stack.get(); String previous = stack.peek(); String segment = args.length == 0 ? format : String.format(format, args); String newValue = previous == null ? segment : String.format("%s %s", previous, segment); stack.push(newValue); MDC.put("NDC", newValue); } }