下面列出了org.slf4j.MDC#put ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
MDC.put("node", node.getId().toString());
try {
if (msg instanceof Frame) {
Frame frame = (Frame) msg;
node.handle(ctx, frame);
} else if (msg instanceof UnsupportedProtocolVersionMessage) {
UnsupportedProtocolVersionMessage umsg = (UnsupportedProtocolVersionMessage) msg;
node.handle(ctx, umsg);
} else {
throw new IllegalArgumentException("Received Invalid message into handler: " + msg);
}
} finally {
MDC.remove("node");
}
}
@Override
protected void initChannel(Channel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
BoundNode node = channel.parent().attr(HANDLER).get();
node.clientChannelGroup.add(channel);
MDC.put("node", node.getId().toString());
try {
logger.debug("Got new connection {}", channel);
pipeline
.addLast(new FlushConsolidationHandler())
.addLast("decoder", new FrameDecoder(node.getFrameCodec()))
.addLast("encoder", new FrameEncoder(node.getFrameCodec()))
.addLast("requestHandler", new RequestHandler(node));
} finally {
MDC.remove("node");
}
}
@Override
public boolean dispatch(SimpleEventType simpleEventType, Object... data) {
Preconditions.checkState(data.length == 2);
Event[] events = new Event[]{(Event) data[0], (Event) data[1]};
BinlogDataId dataId = DataId.fromEvent(events, binlogInfo.get().getBinlogFilename());
MDC.put(LogbackLoggingField.EID, dataId.eventId());
boolean res = true;
for (ConsumerChannel consumerChannel : consumerChannels) {
FilterRes decide = consumerChannel.decide(simpleEventType, dataId, events);
res = res && FilterRes.ACCEPT == decide;
}
MDC.remove(LogbackLoggingField.EID);
return res;
}
@Test
@Repeat(times = 10000, threads = 4)
public void withMDCRunnable() throws ExecutionException, InterruptedException {
MDC.put("foo", "bar");
final CompletableFuture<String> value = new CompletableFuture<>();
EXECUTOR_SERVICE.submit(withMDC(() -> value.complete(MDC.get("foo")))).get();
assertThat(value.get(), is("bar"));
}
@Test
public void testIsProgress() {
startTask();
MDC.put(MDC_MARKER_ID, PROGRESS.getName());
assertThat(taskLogsFilter.decide(event), equalTo(NEUTRAL));
assertNotNull(TaskLoggerHelper.get());
ArgumentCaptor<TaskLoggingEvent> argumentCaptor = ArgumentCaptor.forClass(TaskLoggingEvent.class);
verify(taskLogger).progress(argumentCaptor.capture());
TaskLoggingEvent taskLoggingEvent = argumentCaptor.getValue();
assertNotNull(taskLoggingEvent);
assertThat(taskLoggingEvent.getMessage(), equalTo(TEST_MESSAGE));
assertThat(taskLoggingEvent.getArgumentArray(), equalTo(TEST_ARGS));
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
if (shouldIgnore(request)) {
filterChain.doFilter(request, servletResponse);
return;
}
Account account = extractFromSecurity(request, response);
try {
if (isLogin(account)) {
userContext.setAccount(account);
String ip = RequestUtil.getRealIP(request);
userContext.setIp(ip);
userContext.freshGroupInfos();
MDC.put(MdcConstants.USER_ID, account.getUserId());
MDC.put(MdcConstants.IP, ip);
filterChain.doFilter(request, servletResponse);
} else {
handleUnLogin(servletResponse);
}
} finally {
userContext.clear();
}
}
@Override
public Object run() {
//链路追踪id
String traceId = IdUtil.fastSimpleUUID();
MDC.put(BaseContextConstants.LOG_TRACE_ID, traceId);
RequestContext ctx = RequestContext.getCurrentContext();
ctx.addZuulRequestHeader(BaseContextConstants.TRACE_ID_HEADER, traceId);
return null;
}
private LibraryIdentifier(File appFile) {
this.stats = new AppStats(appFile);
// set identifier for logging
String logIdentifier = LibScoutConfig.logDir.getAbsolutePath() + File.separator;
logIdentifier += appFile.getName().replaceAll("\\.jar", "").replaceAll("\\.apk", "").replaceAll("\\.aar", "");
MDC.put("appPath", logIdentifier);
}
/**
* Enhances the default slf4j {@link org.slf4j.MDC} with a {@code correlationId}.
*
* @param correlationId the optional correlation ID to set.
*/
public static void enhanceLogWithCorrelationId(@Nullable final CharSequence correlationId) {
if (correlationId != null && 0 < correlationId.length()) {
MDC.put(X_CORRELATION_ID, correlationId.toString());
} else {
removeCorrelationId();
}
}
@Test
public void testLogger() throws Exception {
logger.debug(null, "test", "test");
MDC.put("channel","test2");
logger2.debug("1234567");
}
private void runCustomCommand(ICommand cmd, String invoke, List<String> args, GuildMessageReceivedEvent event) {
final CustomCommand cc = (CustomCommand) cmd;
if (cc.getGuildId() != event.getGuild().getIdLong()) {
return;
}
try {
MDC.put("command.custom.message", cc.getMessage());
final Parser parser = CommandUtils.getParser(new CommandContext(invoke, args, event, variables));
final String message = parser.parse(cc.getMessage());
final MessageBuilder messageBuilder = new MessageBuilder();
final DataObject object = parser.get("embed");
if (!message.isEmpty()) {
messageBuilder.setContent("\u200B" + message);
}
if (object != null) {
final JDAImpl jda = (JDAImpl) event.getJDA();
final MessageEmbed embed = jda.getEntityBuilder().createMessageEmbed(object);
messageBuilder.setEmbed(embed);
}
if (!messageBuilder.isEmpty()) {
sendMsg(event, messageBuilder.build());
}
parser.clear();
}
catch (Exception e) {
sendMsg(event, "Error with parsing custom command: " + e.getMessage());
Sentry.capture(e);
}
}
@Test
public void loadsContextFields() throws Exception {
// needs to be set since value default is null
// which removes the request id from the MDC
MDC.put(Fields.REQUEST_ID, "test_request_id");
converter.start();
converter.convert(event);
String[] keys = LogContext.getContextFieldsKeys().toArray(new String[0]);
assertThat(MDC.getCopyOfContextMap().keySet(), hasItems(keys));
}
public void setTargetState(String taskId, TargetState state) {
try {
MDC.put(Constants.MDC_TASKID, taskId);
WorkerTask task = tasks.get(taskId);
if (task != null) {
log.info("Setting task {} state to {}", taskId, state);
task.transitionTo(state);
}
} finally {
MDC.remove(Constants.MDC_TASKID);
}
}
@Override
public void filter(ContainerRequestContext requestContext) {
MDC.put(GATEWAY_ACCOUNT_ID, getAccountId(requestContext));
getPathParameterFromRequest("paymentId", requestContext)
.ifPresent(paymentId -> MDC.put(PAYMENT_EXTERNAL_ID, paymentId));
getPathParameterFromRequest("mandateId", requestContext)
.ifPresent(mandateId -> MDC.put(MANDATE_EXTERNAL_ID, mandateId));
getPathParameterFromRequest("refundId", requestContext)
.ifPresent(refundId -> MDC.put(REFUND_EXTERNAL_ID, refundId));
}
@Override
public DetectorDocument findByUuid(String uuid) {
MDC.put("DetectorUuid", uuid);
val queryBuilder = QueryBuilders.termQuery("uuid", uuid);
val searchSourceBuilder = elasticsearchUtil.getSourceBuilder(queryBuilder).size(DEFAULT_ES_RESULTS_SIZE);
val searchRequest = elasticsearchUtil.getSearchRequest(searchSourceBuilder, DETECTOR_INDEX, DETECTOR_DOC_TYPE);
val detectors = getDetectorsFromElasticSearch(searchRequest);
MDC.remove("DetectorUuid");
return detectors.isEmpty() ? null : detectors.get(0);
}
/**
* The method will get triggered from Rule Engine with following parameters
*
* @param ruleParam
*
* ************* Following are the Rule Parameters********* <br>
* <br>
*
* ruleKey : check-for-improper-roles-name <br>
* <br>
*
* threadsafe : if true , rule will be executed on multiple
* threads <br>
* <br>
*
* severity : Enter the value of severity <br>
* <br>
*
* ruleCategory : Enter the value of category <br>
* <br>
*
* @param resourceAttributes
* this is a resource in context which needs to be scanned this
* is provided by execution engine
*
*/
@Override
public RuleResult execute(Map<String, String> ruleParam,
Map<String, String> resourceAttributes) {
logger.debug("========CheckImproperRolesNamesRule started=========");
Annotation annotation = null;
String resourceId = null;
String severity = ruleParam.get(PacmanRuleConstants.SEVERITY);
String category = ruleParam.get(PacmanRuleConstants.CATEGORY);
MDC.put("executionId", ruleParam.get("executionId"));
MDC.put("ruleId", ruleParam.get(PacmanSdkConstants.RULE_ID));
List<LinkedHashMap<String, Object>> issueList = new ArrayList<>();
LinkedHashMap<String, Object> issue = new LinkedHashMap<>();
if (!PacmanUtils.doesAllHaveValue(severity, category)) {
logger.info(PacmanRuleConstants.MISSING_CONFIGURATION);
throw new InvalidInputException(PacmanRuleConstants.MISSING_CONFIGURATION);
}
if (resourceAttributes != null) {
resourceId = resourceAttributes.get(PacmanSdkConstants.RESOURCE_ID);
if (StringUtils.containsWhitespace(resourceId)) {
annotation = Annotation.buildAnnotation(ruleParam,
Annotation.Type.ISSUE);
annotation.put(PacmanSdkConstants.DESCRIPTION,
"Improper roles name found !!");
annotation.put(PacmanRuleConstants.SEVERITY, severity);
annotation.put(PacmanRuleConstants.CATEGORY, category);
issue.put(PacmanRuleConstants.VIOLATION_REASON,
" Role name with space found");
issueList.add(issue);
annotation.put("issueDetails", issueList.toString());
logger.debug(
"========CheckImproperRolesNamesRule with annotation : {} =========",
annotation);
return new RuleResult(PacmanSdkConstants.STATUS_FAILURE,
PacmanRuleConstants.FAILURE_MESSAGE, annotation);
}
}
logger.debug("========CheckImproperRolesNamesRule ended=========");
return new RuleResult(PacmanSdkConstants.STATUS_SUCCESS,
PacmanRuleConstants.SUCCESS_MESSAGE);
}
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
// Make sure the cores is enabled
try {
CoreContainer cores = getCoreContainer();
if (cores == null) {
throw new SolrException(ErrorCode.BAD_REQUEST,
"Core container instance missing");
}
//boolean doPersist = false;
final String taskId = req.getParams().get(CommonAdminParams.ASYNC);
final TaskObject taskObject = new TaskObject(taskId);
if(taskId != null) {
// Put the tasks into the maps for tracking
if (getRequestStatusMap(RUNNING).containsKey(taskId) || getRequestStatusMap(COMPLETED).containsKey(taskId) || getRequestStatusMap(FAILED).containsKey(taskId)) {
throw new SolrException(ErrorCode.BAD_REQUEST,
"Duplicate request with the same requestid found.");
}
addTask(RUNNING, taskObject);
}
// Pick the action
CoreAdminOperation op = opMap.get(req.getParams().get(ACTION, STATUS.toString()).toLowerCase(Locale.ROOT));
if (op == null) {
handleCustomAction(req, rsp);
return;
}
final CallInfo callInfo = new CallInfo(this, req, rsp, op);
String coreName = req.getParams().get(CoreAdminParams.CORE);
if (coreName == null) {
coreName = req.getParams().get(CoreAdminParams.NAME);
}
MDCLoggingContext.setCoreName(coreName);
if (taskId == null) {
callInfo.call();
} else {
try {
MDC.put("CoreAdminHandler.asyncId", taskId);
MDC.put("CoreAdminHandler.action", op.action.toString());
parallelExecutor.execute(() -> {
boolean exceptionCaught = false;
try {
callInfo.call();
taskObject.setRspObject(callInfo.rsp);
} catch (Exception e) {
exceptionCaught = true;
taskObject.setRspObjectFromException(e);
} finally {
removeTask("running", taskObject.taskId);
if (exceptionCaught) {
addTask("failed", taskObject, true);
} else {
addTask("completed", taskObject, true);
}
}
});
} finally {
MDC.remove("CoreAdminHandler.asyncId");
MDC.remove("CoreAdminHandler.action");
}
}
} finally {
rsp.setHttpCaching(false);
}
}
@Override
public boolean putMdc(String key, String value) {
MDC.put(key, value);
return true;
}
@Override
protected void runInContext() {
final long seq = this._req.getSequence();
try {
final ServerResource resource = DirectAgentAttache.this._resource;
final Command[] cmds = this._req.getCommands();
final boolean stopOnError = this._req.stopOnError();
if (s_logger.isDebugEnabled()) {
s_logger.debug(log(seq, "Executing request"));
}
final ArrayList<Answer> answers = new ArrayList<>(cmds.length);
for (int i = 0; i < cmds.length; i++) {
Answer answer = null;
final Command currentCmd = cmds[i];
if (currentCmd.getContextParam("logid") != null) {
MDC.put("logcontextid", currentCmd.getContextParam("logid"));
}
if (resource != null) {
answer = resource.executeRequest(cmds[i]);
if (answer == null) {
s_logger.warn("Resource returned null answer!");
answer = new Answer(cmds[i], false, "Resource returned null answer");
}
} else {
answer = new Answer(cmds[i], false, "Agent is disconnected");
}
answers.add(answer);
if (!answer.getResult() && stopOnError) {
if (i < cmds.length - 1 && s_logger.isDebugEnabled()) {
s_logger.debug(log(seq, "Cancelling because one of the answers is false and it is stop on error."));
}
break;
}
}
final Response resp = new Response(this._req, answers.toArray(new Answer[answers.size()]));
if (s_logger.isDebugEnabled()) {
s_logger.debug(log(seq, "Response Received: "));
}
processAnswers(seq, resp);
} finally {
DirectAgentAttache.this._outstandingTaskCount.decrementAndGet();
scheduleFromQueue();
}
}
@Test
public void testIsInternalProgress() {
startTask();
MDC.put(MDC_MARKER_ID, INTERNAL_PROGRESS.getName());
assertThat(taskLogsFilter.decide(event), equalTo(DENY));
}