下面列出了org.slf4j.MDC#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public synchronized void unRegisterEndpointInstance(String destination) {
String oldMDC = MDC.get(Constants.MDC_TASKID);
try {
MDC.put(Constants.MDC_TASKID, gwCanal.getName());
logger.info("unregister an endpoint instance with name {} begin.", destination);
if (endpointInstances.containsKey(destination)) {
endpointInstances.remove(destination);
unRegisterInternal(destination);
refreshAlarmHandler();
} else {
logger.info("no need to execute unregister,because this instance has been kicked out in other time.");
}
logger.info("unregister an endpoint instance with name {} end.", destination);
} finally {
if (StringUtils.isNotBlank(oldMDC)) {
MDC.put(Constants.MDC_TASKID, oldMDC);
} else {
MDC.remove(Constants.MDC_TASKID);
}
}
}
static Problem createProblem(String detail, int code) {
String traceId = MDC.get("traceId");
if (traceId != null) {
return Problem.builder().withDetail(detail).with("code", code).with("traceId", traceId)
.withStatus(Status.OK).build();
} else {
return Problem.builder().withDetail(detail).with("code", code).withStatus(Status.OK).build();
}
}
/**
* Event based on an HttpServletRequest, typically used during authentication.
* Solr will fill in details such as ip, http method etc from the request, and
* username if Principal exists on the request.
* @param eventType a predefined or custom EventType
* @param httpRequest the request to initialize from
*/
public AuditEvent(EventType eventType, Throwable exception, HttpServletRequest httpRequest) {
this(eventType);
this.solrHost = httpRequest.getLocalName();
this.solrPort = httpRequest.getLocalPort();
this.solrIp = httpRequest.getLocalAddr();
this.clientIp = httpRequest.getRemoteAddr();
this.httpMethod = httpRequest.getMethod();
this.httpQueryString = httpRequest.getQueryString();
this.headers = getHeadersFromRequest(httpRequest);
this.baseUrl = httpRequest.getRequestURL().toString();
this.nodeName = MDC.get(ZkStateReader.NODE_NAME_PROP);
SolrRequestParsers.parseQueryString(httpQueryString).forEach(sp -> {
this.solrParams.put(sp.getKey(), Arrays.asList(sp.getValue()));
});
setResource(ServletUtils.getPathAfterContext(httpRequest));
setRequestType(findRequestType());
if (exception != null) setException(exception);
Principal principal = httpRequest.getUserPrincipal();
if (principal != null) {
this.username = httpRequest.getUserPrincipal().getName();
} else if (eventType.equals(EventType.AUTHENTICATED)) {
this.eventType = ANONYMOUS;
this.message = ANONYMOUS.message;
this.level = ANONYMOUS.level;
log.debug("Audit event type changed from AUTHENTICATED to ANONYMOUS since no Principal found on request");
}
}
private static long calculateElapsedTime() {
long endTime = System.currentTimeMillis();
String startTimeS = MDC.get("startTime");
if (startTimeS == null)
return -1;
long startTime = Long.parseLong(startTimeS);
return endTime - startTime;
}
public ContextHolder getContext() {
ContextHolder holder = new ContextHolder();
holder.guildId = guildHolder.get();
holder.locale = localeHolder.get();
holder.color = colorHolder.get();
holder.userId = MDC.get(MDC_USER);
return holder;
}
private void enqueueImplementation(final String message, String token, final long timeSpent, boolean ShowValue, String... tags) {
final String passedToken;
if (token == null) {
passedToken = MDC.get(ProfiledMeasure.MDC_UUID_TOKEN_KEY);
} else {
passedToken = token;
}
measuresQueue.add(new ProfiledMeasure(message, timeSpent, ShowValue, tags, passedToken));
}
@Override
public void run() {
SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
SofaTracerSpan currentSpan = sofaTraceContext.getCurrentSpan();
Assert.assertTrue(currentSpan != mockSpan);
String traceIdMdc = MDC.get(MDCKeyConstants.MDC_TRACEID);
Assert.assertTrue(traceId.equals(traceIdMdc));
}
/**
* Logs the HTTP status code and exception in HttpFSServer's log.
*
* @param status HTTP status code.
* @param throwable exception thrown.
*/
@Override
protected void log(Response.Status status, Throwable throwable) {
String method = MDC.get("method");
String path = MDC.get("path");
String message = getOneLineMessage(throwable);
AUDIT_LOG.warn("FAILED [{}:{}] response [{}] {}", new Object[]{method, path, status, message});
LOG.warn("[{}:{}] response [{}] {}", new Object[]{method, path, status, message}, throwable);
}
@DataProvider(value = {
"null",
"",
"TRACE_ID",
"TRACE_ID,SPAN_ID,PARENT_SPAN_ID,FULL_SPAN_JSON"
}, splitBy = "\\|")
@Test
public void configureMDC_should_set_span_values_on_MDC_based_on_spanFieldsForLoggerMdc(
String rawSpanFields
) {
// given
Span span = Span.newBuilder("test-span", SpanPurpose.LOCAL_ONLY)
.withParentSpanId("3")
.withTag("fooTag", "fooTagValue")
.withTimestampedAnnotation(Span.TimestampedAnnotation.forCurrentTime("fooEvent"))
.build();
Set<SpanFieldForLoggerMdc> spanFieldsForMdc = parseRawSpanFieldsForMdc(rawSpanFields);
Tracer.getInstance().setSpanFieldsForLoggerMdc(spanFieldsForMdc);
// when
Tracer.getInstance().configureMDC(span);
// then
for (SpanFieldForLoggerMdc fieldForMdc : SpanFieldForLoggerMdc.values()) {
String actualMdcValue = MDC.get(fieldForMdc.mdcKey);
if (spanFieldsForMdc != null && spanFieldsForMdc.contains(fieldForMdc)) {
assertThat(actualMdcValue).isEqualTo(fieldForMdc.getMdcValueForSpan(span));
}
else {
assertThat(actualMdcValue).isNull();
}
}
}
@Override
public FilterReply decide(final ILoggingEvent event) {
String marker = MDC.get(MDC_MARKER_ID);
if (MDC.get(TASK_LOG_WITH_PROGRESS_MDC) != null && INTERNAL_PROGRESS.getName().equals(marker)) {
// internal progress logs for TaskLogType.TASK_LOG_WITH_PROGRESS are wanted
return NEUTRAL;
}
if (DENY_MARKERS.stream().anyMatch(m -> m.getName().equals(marker)) || MDC.get(TASK_LOG_ONLY_MDC) != null) {
return DENY;
}
return NEUTRAL;
}
private static void tagCommand(final Command cmd) {
final AsyncJobExecutionContext context = AsyncJobExecutionContext.getCurrent();
if (context != null && context.getJob() != null) {
final AsyncJob job = context.getJob();
if (job.getRelated() != null && !job.getRelated().isEmpty()) {
cmd.setContextParam("job", "job-" + job.getRelated() + "/" + "job-" + job.getId());
} else {
cmd.setContextParam("job", "job-" + job.getId());
}
}
if (MDC.get("logcontextid") != null && !MDC.get("logcontextid").isEmpty()) {
cmd.setContextParam("logid", MDC.get("logcontextid"));
}
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
String user = MDC.get(LogConstants.USER);
String entity = MDC.get(LogConstants.ENTITY);
List<SafeCallable<T>> wrappedTasks = new ArrayList<>(tasks.size());
for (Callable<T> task : tasks) {
wrappedTasks.add(new SafeCallable<T>(user, entity, task, true));
}
return super.invokeAny(wrappedTasks);
}
@Override
public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
if (MDC.get("userid") == null) {
MDC.put("userid", System.getProperty("user.name"));
}
return FilterReply.NEUTRAL;
}
@Override
public Future<?> submit(final Runnable runnable) {
String user = MDC.get(LogConstants.USER);
String entity = MDC.get(LogConstants.ENTITY);
return super.submit(new SafeRunnable(user, entity, runnable, true));
}
public void scheduleWithFixedDelayAndForget(Runnable command, long initialDelay, long period, TimeUnit unit) {
String user = MDC.get(LogConstants.USER);
String entity = MDC.get(LogConstants.ENTITY);
super.scheduleWithFixedDelay(new SafeRunnable(user, entity, command, false), initialDelay, period, unit);
}
private void logContentStart(StringBuilder stringBuilder, String logKey, String prefix,
String tail) {
String appendString = MDC.get(logKey);
stringBuilder.append(prefix).append((appendString == null ? "" : appendString)).append(tail);
}
@Override
public <T> Future<T> submit(Callable<T> task) {
String user = MDC.get(LogConstants.USER);
String entity = MDC.get(LogConstants.ENTITY);
return super.submit(new SafeCallable<>(user, entity, task, true));
}
public void submitAndForget(final Runnable runnable) {
String user = MDC.get(LogConstants.USER);
String entity = MDC.get(LogConstants.ENTITY);
super.submit(new SafeRunnable(user, entity, runnable, false));
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
String user = MDC.get(LogConstants.USER);
String entity = MDC.get(LogConstants.ENTITY);
return super.scheduleAtFixedRate(new SafeRunnable(user, entity, command, true), initialDelay, period, unit);
}
/**
* 未設定の場合のみMDCの値を設定します。
*
* @param key
* @param value
*/
public static void putIfAbsent(String key, String value) {
if (MDC.get(key) == null)
MDC.put(key, value);
}