org.apache.log4j.MDC Java Examples
The following examples show how to use
org.apache.log4j.MDC.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SourcePipe.java From datacollector with Apache License 2.0 | 6 votes |
/** * Process method for Push source that will give control of the execution to the origin. * * @param offsets Offsets from last execution * @param batchSize Maximal configured batch size */ public void process( Map<String, String> offsets, int batchSize, ReportErrorDelegate reportErrorDelegate ) throws StageException, PipelineRuntimeException { this.reportErrorDelegate = reportErrorDelegate; getStage().setReportErrorDelegate(this); try { MDC.put(LogConstants.STAGE, getStage().getInfo().getInstanceName()); getStage().execute(offsets, batchSize); } finally { MDC.put(LogConstants.STAGE, ""); } }
Example #2
Source File: DocumentAttributeIndexingQueueImpl.java From rice with Educational Community License v2.0 | 6 votes |
@Override public void indexDocument(String documentId) { if (StringUtils.isBlank(documentId)) { throw new RiceIllegalArgumentException("documentId was null or blank"); } MDC.put("docId", documentId); try { long t1 = System.currentTimeMillis(); LOG.info("Indexing document attributes for document " + documentId); Document document = getWorkflowDocumentService().getDocument(documentId); if (document == null) { throw new RiceIllegalArgumentException("Failed to locate document with the given id: " + documentId); } DocumentContent documentContent = KewApiServiceLocator.getWorkflowDocumentService().getDocumentContent(documentId); List<SearchableAttributeValue> attributes = buildSearchableAttributeValues(document, documentContent); KEWServiceLocator.getRouteHeaderService().updateRouteHeaderSearchValues(documentId, attributes); long t2 = System.currentTimeMillis(); LOG.info("...finished indexing document " + documentId + " for document search, total time = " + (t2 - t1) + " ms."); } finally { MDC.remove("docId"); } }
Example #3
Source File: DefaultConsoleAppenderTest.java From lambda-monitoring with Apache License 2.0 | 6 votes |
@Test public void testMDC() { PrintStream original = System.out; try { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); System.setOut(new PrintStream(outputStream, true)); MDC.put("AWSRequestId", "AWS-REQUEST-ID"); Logger logger = LoggerFactory.getLogger("TEST-LOGGER"); logger.info("TEST-MESSAGE"); assertThat(outputStream.toString(), matchesPattern("^\\[[0-9\\-:\\. ]{23}\\] AWS-REQUEST-ID INFO TEST-LOGGER - TEST-MESSAGE \\r\\n$")); } finally { System.setOut(original); } }
Example #4
Source File: Log4jAuditor.java From knox with Apache License 2.0 | 6 votes |
private void auditLog( String action, String resourceName, String resourceType, String outcome, String message ) { if ( logger.isInfoEnabled() ) { MDC.put( AuditConstants.MDC_ACTION_KEY, action ); MDC.put( AuditConstants.MDC_RESOURCE_NAME_KEY, maskTokenFromURL(resourceName) ); MDC.put( AuditConstants.MDC_RESOURCE_TYPE_KEY, resourceType ); MDC.put( AuditConstants.MDC_OUTCOME_KEY, outcome ); MDC.put( AuditConstants.MDC_SERVICE_KEY, serviceName ); MDC.put( AuditConstants.MDC_COMPONENT_KEY, componentName ); logger.info( message ); MDC.remove( AuditConstants.MDC_ACTION_KEY ); MDC.remove( AuditConstants.MDC_RESOURCE_NAME_KEY ); MDC.remove( AuditConstants.MDC_RESOURCE_TYPE_KEY ); MDC.remove( AuditConstants.MDC_OUTCOME_KEY ); MDC.remove( AuditConstants.MDC_SERVICE_KEY ); MDC.remove( AuditConstants.MDC_COMPONENT_KEY ); } }
Example #5
Source File: Log4JContextClearingFilter.java From rice with Educational Community License v2.0 | 6 votes |
/** * Get the Log4J MDC threadlocal via reflection * @return the MDC ThreadLocalMap object or null if unset or error */ protected static ThreadLocal getMDCThreadLocal() { try { Field mdcField = MDC.class.getDeclaredField("mdc"); if (mdcField != null) { mdcField.setAccessible(true); Object mdc = mdcField.get(null); Field tlmField = MDC.class.getDeclaredField("tlm"); if (tlmField != null) { tlmField.setAccessible(true); return (ThreadLocal) tlmField.get(mdc); } } } catch (NoSuchFieldException nsfe) { nsfe.printStackTrace(); } catch (IllegalAccessException iae) { iae.printStackTrace(); } return null; }
Example #6
Source File: AgentManagerImpl.java From cloudstack with Apache License 2.0 | 6 votes |
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()); } } String logcontextid = (String) MDC.get("logcontextid"); if (!Strings.isNullOrEmpty(logcontextid)) { cmd.setContextParam("logid", logcontextid); } }
Example #7
Source File: LoggerUtil.java From Bats with Apache License 2.0 | 6 votes |
/** * Makes MDC properties */ public static void setupMDC(String service) { MDC.put("apex.service", service); String value = StramClientUtils.getHostName(); MDC.put("apex.node", value == null ? "unknown" : value); value = System.getenv(Environment.USER.key()); if (value != null) { MDC.put("apex.user", value); } value = System.getenv(Environment.CONTAINER_ID.name()); if (value != null) { ContainerId containerId = ConverterUtils.toContainerId(value); ApplicationId applicationId = containerId.getApplicationAttemptId().getApplicationId(); MDC.put("apex.containerId", containerId.toString()); MDC.put("apex.applicationId", applicationId.toString()); } value = System.getProperty(APPLICATION_NAME.getLongName()); if (value != null) { MDC.put("apex.application", value); } }
Example #8
Source File: PlatformSubsystemExecutor.java From arcusplatform with Apache License 2.0 | 6 votes |
public void dispatch(MessageReceivedEvent event, IrisCorrelator<ResponseAction<?>> correlator) { MDC.put(MdcContext.MDC_TARGET, address.getRepresentation()); context.setActor(event.getMessage().getActor()); if(!context.isPersisted()) { dispatchEvent(SubsystemLifecycleEvent.added(address)); } if(context.isDeleted()) { context.logger().warn("Dropping event to deleted subsystem [{}]", event); } else { Result<ResponseAction<?>> result = correlator.correlate(event.getMessage()); if(result != null) { if(result.isError()) { context.logger().warn("Error correlating response [{}}", event.getMessage(), result.getError()); } else { dispatchEvent(SubsystemResponseEvent.response(address, result.getValue(), event.getMessage())); } } dispatchEvent(event); save(event); } }
Example #9
Source File: RestaurantServiceAPI.java From Mastering-Microservices-with-Java with MIT License | 5 votes |
/** * Fetch restaurants with the specified name. A partial case-insensitive * match is supported. So <code>http://.../restaurants/rest</code> will find * any restaurants with upper or lower case 'rest' in their name. * * @param name * @return A non-null, non-empty collection of restaurants. */ @HystrixCommand(fallbackMethod = "defaultRestaurants") @RequestMapping(method = RequestMethod.GET) public ResponseEntity<Collection<Restaurant>> findByName(@RequestParam("name") String name) { LOG.info(String.format("api-service findByName() invoked:{} for {} ", "v1/restaurants?name=", name)); MDC.put("restaurantId", name); String url = "http://restaurant-service/v1/restaurants?name=".concat(name); LOG.debug("GetRestaurant from URL: {}", url); Collection<Restaurant> restaurants; ResponseEntity<Collection> result = restTemplate.getForEntity(url, Collection.class); LOG.info("GetRestaurant http-status: {}", result.getStatusCode()); LOG.debug("GetRestaurant body: {}", result.getBody()); return serviceHelper.createOkResponse(result.getBody()); }
Example #10
Source File: XMLLayoutTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * Clear MDC and NDC before test. */ public void setUp() { NDC.clear(); if (MDC.getContext() != null) { MDC.getContext().clear(); } }
Example #11
Source File: MDCUserServletFilter.java From bamboobsc with Apache License 2.0 | 5 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpSession session = httpRequest.getSession(); boolean setUserId = false; if ( session != null && session.getAttribute(Constants.SESS_ACCOUNT) != null ) { String accountId = ((AccountObj)session.getAttribute(Constants.SESS_ACCOUNT)).getAccount(); MDC.put(_USERID_KEY_NAME, accountId); setUserId = true; } if (!setUserId) { String url = httpRequest.getRequestURL().toString(); if (url.indexOf("/services/") > -1) { MDC.put(_USERID_KEY_NAME, "CXF-WEBSERVICE"); setUserId = true; } if (url.indexOf("/camel/") > -1) { MDC.put(_USERID_KEY_NAME, "CAMEL-ESB"); setUserId = true; } } try { chain.doFilter(request, response); } catch (ServletException | IOException e) { e.printStackTrace(); } finally { if (setUserId) { MDC.remove(_USERID_KEY_NAME); } } }
Example #12
Source File: TrackingLogger.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 5 votes |
@Override public void handleNotification(Notification notification, Object handback) { JMXNotificationMessage message = (JMXNotificationMessage) notification.getUserData(); Object oldRunId = MDC.get(LogUtils.MDC_RUNID_KEY); MDC.put(LogUtils.MDC_RUNID_KEY, Long.valueOf(message.getRunId())); try { if(notification.getType().equals(CloverJMX.GRAPH_STARTED)) { graphStarted(); } else if(notification.getType().equals(CloverJMX.TRACKING_UPDATED)) { trackingUpdated(); } else if(notification.getType().equals(CloverJMX.PHASE_FINISHED)) { phaseFinished(); } else if(notification.getType().equals(CloverJMX.PHASE_ABORTED)) { phaseAborted(); } else if(notification.getType().equals(CloverJMX.PHASE_ERROR)) { phaseError(); } else if(notification.getType().equals(CloverJMX.GRAPH_FINISHED) || notification.getType().equals(CloverJMX.GRAPH_ABORTED) || notification.getType().equals(CloverJMX.GRAPH_ERROR)) { graphFinished(); try { CloverJMX.getInstance().removeNotificationListener(this); } catch (ListenerNotFoundException e) { logger.warn("Unexpected error while graph logging will be ignored."); } } } finally { if (oldRunId == null) { MDC.remove(LogUtils.MDC_RUNID_KEY); } else { MDC.put(LogUtils.MDC_RUNID_KEY, oldRunId); } } }
Example #13
Source File: TaskLogger.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
public void debug(TaskId id, String message, Throwable th) { if (logger.isDebugEnabled()) { updateMdcWithTaskLogFilename(id); logger.debug(format(id, message), th); MDC.remove(FileAppender.FILE_NAME); } }
Example #14
Source File: TaskLogger.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
public void debug(TaskId id, String message) { if (logger.isDebugEnabled()) { updateMdcWithTaskLogFilename(id); logger.debug(format(id, message)); MDC.remove(FileAppender.FILE_NAME); } }
Example #15
Source File: AcknowledgeAction.java From rice with Educational Community License v2.0 | 5 votes |
/** * Records the Acknowldege action. - Checks to make sure the document status allows the action. - Checks that the user has not taken a previous action. - Deactivates the pending requests for this user - Records the action * * @throws InvalidActionTakenException * @throws ResourceUnavailableException */ public void recordAction() throws InvalidActionTakenException { MDC.put("docId", getRouteHeader().getDocumentId()); updateSearchableAttributesIfPossible(); LOG.debug("Acknowledging document : " + annotation); LOG.debug("Checking to see if the action is legal"); List actionRequests = getActionRequestService().findAllValidRequests(getPrincipal().getPrincipalId(), routeHeader.getDocumentId(), KewApiConstants.ACTION_REQUEST_ACKNOWLEDGE_REQ); if (actionRequests == null || actionRequests.isEmpty()) { DocumentTypePolicy allowUnrequested = getRouteHeader().getDocumentType().getAllowUnrequestedActionPolicy(); if (allowUnrequested != null) { if (!allowUnrequested.getPolicyValue()) { throw new InvalidActionTakenException("No request for the user is compatible " + "with the ACKNOWLEDGE action. " + "Doctype policy ALLOW_UNREQUESTED_ACTION is set to false and someone else likely just took action on the document."); } } } String errorMessage = validateActionRules(actionRequests); if (!org.apache.commons.lang.StringUtils.isEmpty(errorMessage)) { throw new InvalidActionTakenException(errorMessage); } LOG.debug("Record the acknowledge action"); Recipient delegator = findDelegatorForActionRequests(actionRequests); ActionTakenValue actionTaken = saveActionTaken(delegator); LOG.debug("Deactivate all pending action requests"); getActionRequestService().deactivateRequests(actionTaken, actionRequests); notifyActionTaken(actionTaken); }
Example #16
Source File: JobLogger.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
public void flush(JobId id) { updateMdcWithTaskLogFilename(id); logger.debug(PREFIX + id + " closing logger"); for (Appender appender : (List<Appender>) Collections.list(logger.getAllAppenders())) { if (appender instanceof AsynchFileAppender) { ((AsynchFileAppender) appender).flush(); } } MDC.remove(FileAppender.FILE_NAME); }
Example #17
Source File: JobLogger.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
public void close(JobId id) { updateMdcWithTaskLogFilename(id); logger.debug(PREFIX + id + " closing logger"); for (Appender appender : (List<Appender>) Collections.list(logger.getAllAppenders())) { if (appender != null && appender instanceof FileAppender) { appender.close(); } } MDC.remove(FileAppender.FILE_NAME); }
Example #18
Source File: CloverJMX.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 5 votes |
@Override public GraphTracking getGraphTracking(long runId) { Object oldRunId = MDC.get(LogUtils.MDC_RUNID_KEY); MDC.put(LogUtils.MDC_RUNID_KEY, runId); try { return getWatchDog(runId).getGraphTracking(); } finally { if (oldRunId == null) { MDC.remove(LogUtils.MDC_RUNID_KEY); } else { MDC.put(LogUtils.MDC_RUNID_KEY, oldRunId); } } }
Example #19
Source File: PurgeUtilityLogger.java From pentaho-kettle with Apache License 2.0 | 5 votes |
private void setCodeLine() { for ( int stackLevel = 1; stackLevel < Thread.currentThread().getStackTrace().length; stackLevel++ ) { StackTraceElement ste = Thread.currentThread().getStackTrace()[stackLevel]; if ( !ste.getClassName().equals( this.getClass().getName() ) ) { MDC.put( CODE_LINE, ste.getClassName() + "." + ste.getMethodName() + ":" + ste.getLineNumber() ); break; } } }
Example #20
Source File: RestaurantServiceAPI.java From Mastering-Microservices-with-Java with MIT License | 5 votes |
@RequestMapping("/restaurants/{restaurant-id}") @HystrixCommand(fallbackMethod = "defaultRestaurant") public ResponseEntity<Restaurant> getRestaurant( @PathVariable("restaurant-id") int restaurantId) { MDC.put("restaurantId", restaurantId); String url = "http://restaurant-service/v1/restaurants/" + restaurantId; LOG.debug("GetRestaurant from URL: {}", url); ResponseEntity<Restaurant> result = restTemplate.getForEntity(url, Restaurant.class); LOG.info("GetRestaurant http-status: {}", result.getStatusCode()); LOG.debug("GetRestaurant body: {}", result.getBody()); return serviceHelper.createOkResponse(result.getBody()); }
Example #21
Source File: Log4jIT.java From pinpoint with Apache License 2.0 | 5 votes |
@Test public void test() { Logger logger = Logger.getLogger(getClass()); logger.error("maru"); Assert.assertNotNull(MDC.get("PtxId")); Assert.assertNotNull(MDC.get("PspanId")); }
Example #22
Source File: MDCCurrentTraceContextTest.java From brave with Apache License 2.0 | 5 votes |
@Override protected void verifyImplicitContext(@Nullable TraceContext context) { if (context != null) { assertThat(MDC.get("traceId")).isEqualTo(context.traceIdString()); assertThat(MDC.get("spanId")).isEqualTo(context.spanIdString()); } else { assertThat(MDC.get("traceId")).isNull(); assertThat(MDC.get("spanId")).isNull(); } }
Example #23
Source File: ClearFYIAction.java From rice with Educational Community License v2.0 | 5 votes |
/** * Processes the clear FYI action. - Checks to make sure the document status allows the action. - Checks that the user has not taken a previous action. - Deactivates the pending requests for this user * * @throws InvalidActionTakenException * @throws ResourceUnavailableException */ public void recordAction() throws InvalidActionTakenException { MDC.put("docId", getRouteHeader().getDocumentId()); updateSearchableAttributesIfPossible(); LOG.debug("Clear FYI for document : " + annotation); LOG.debug("Checking to see if the action is legal"); List actionRequests = getActionRequestService().findAllValidRequests(getPrincipal().getPrincipalId(), getDocumentId(), KewApiConstants.ACTION_REQUEST_FYI_REQ); if (actionRequests == null || actionRequests.isEmpty()) { DocumentTypePolicy allowUnrequested = getRouteHeader().getDocumentType().getAllowUnrequestedActionPolicy(); if (allowUnrequested != null) { if (!allowUnrequested.getPolicyValue()) { throw new InvalidActionTakenException("No request for the user is compatible " + "with the ClearFYI action. " + "Doctype policy ALLOW_UNREQUESTED_ACTION is set to false and someone else likely just took action on the document."); } } } String errorMessage = validateActionRules(actionRequests); if (!org.apache.commons.lang.StringUtils.isEmpty(errorMessage)) { throw new InvalidActionTakenException(errorMessage); } ActionTakenValue actionTaken = saveActionTaken(findDelegatorForActionRequests(actionRequests)); LOG.debug("Deactivate all pending action requests"); getActionRequestService().deactivateRequests(actionTaken, actionRequests); notifyActionTaken(actionTaken); }
Example #24
Source File: AuditBatchQueue.java From ranger with Apache License 2.0 | 5 votes |
@Override public void run() { try { //This is done to clear the MDC context to avoid issue with Ranger Auditing for Knox MDC.clear(); runLogAudit(); } catch (Throwable t) { logger.fatal("Exited thread abnormaly. queue=" + getName(), t); } }
Example #25
Source File: TaskLogger.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
public void close(TaskId id) { updateMdcWithTaskLogFilename(id); logger.debug(format(id, "closing logger")); for (Appender appender : (List<Appender>) Collections.list(logger.getAllAppenders())) { if (appender != null && appender instanceof FileAppender) { appender.close(); } } MDC.remove(FileAppender.FILE_NAME); }
Example #26
Source File: LogContext.java From cloudstack with Apache License 2.0 | 5 votes |
public static void unregister() { LogContext context = s_currentContext.get(); if (context != null) { s_currentContext.remove(); if (s_logger.isTraceEnabled()) { s_logger.trace("Unregistered: " + context); } } MDC.clear(); }
Example #27
Source File: RestaurantServiceAPI.java From Microservices-Building-Scalable-Software with MIT License | 5 votes |
/** * Fetch restaurants with the specified name. A partial case-insensitive * match is supported. So <code>http://.../restaurants?name=rest</code> will * find any restaurants with upper or lower case 'rest' in their name. * * @param name * @return A non-null, non-empty collection of restaurants. */ @RequestMapping("") @HystrixCommand(fallbackMethod = "defaultRestaurants") public ResponseEntity<Collection<Restaurant>> findByName(@RequestParam("name") String name) { LOG.info(String.format("api-service findByName() invoked:{} for {} ", "v1/restaurants?name=", name)); MDC.put("restaurantId", name); String url = "http://restaurant-service/v1/restaurants?name=".concat(name); LOG.debug("GetRestaurant from URL: {}", url); Collection<Restaurant> restaurants; ResponseEntity<Collection> result = restTemplate.getForEntity(url, Collection.class); LOG.info("GetRestaurant http-status: {}", result.getStatusCode()); LOG.debug("GetRestaurant body: {}", result.getBody()); return serviceHelper.createResponse(result.getBody(), result.getStatusCode()); }
Example #28
Source File: RestaurantServiceAPI.java From Microservices-Building-Scalable-Software with MIT License | 5 votes |
/** * * @param restaurantId * @return */ @RequestMapping("/{restaurant-id}") @HystrixCommand(fallbackMethod = "defaultRestaurant") public ResponseEntity<Restaurant> getRestaurant( @PathVariable("restaurant-id") int restaurantId) { MDC.put("restaurantId", restaurantId); String url = "http://restaurant-service/v1/restaurants/" + restaurantId; LOG.debug("GetRestaurant from URL: {}", url); ResponseEntity<Restaurant> result = restTemplate.getForEntity(url, Restaurant.class); LOG.info("GetRestaurant http-status: {}", result.getStatusCode()); LOG.debug("GetRestaurant body: {}", result.getBody()); return serviceHelper.createResponse(result.getBody(), result.getStatusCode()); }
Example #29
Source File: RestaurantServiceAPI.java From Mastering-Microservices-with-Java with MIT License | 5 votes |
/** * Fetch restaurants with the specified name. A partial case-insensitive * match is supported. So <code>http://.../restaurants/rest</code> will find * any restaurants with upper or lower case 'rest' in their name. * * @param name * @return A non-null, non-empty collection of restaurants. */ @HystrixCommand(fallbackMethod = "defaultRestaurants") @RequestMapping(method = RequestMethod.GET) public ResponseEntity<Collection<Restaurant>> findByName(@RequestParam("name") String name) { LOG.info(String.format("api-service findByName() invoked:{} for {} ", "v1/restaurants?name=", name)); MDC.put("restaurantId", name); String url = "http://restaurant-service/v1/restaurants?name=".concat(name); LOG.debug("GetRestaurant from URL: {}", url); Collection<Restaurant> restaurants; ResponseEntity<Collection> result = restTemplate.getForEntity(url, Collection.class); LOG.info("GetRestaurant http-status: {}", result.getStatusCode()); LOG.debug("GetRestaurant body: {}", result.getBody()); return serviceHelper.createOkResponse(result.getBody()); }
Example #30
Source File: LoggingEventTest.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * Serialize a logging event with mdc. * @throws Exception if exception during test. * */ public void testSerializationMDC() throws Exception { Logger root = Logger.getRootLogger(); MDC.put("mdckey", "mdcvalue"); LoggingEvent event = new LoggingEvent( root.getClass().getName(), root, Level.INFO, "Hello, world.", null); // event.prepareForDeferredProcessing(); int[] skip = new int[] { 352, 353, 354, 355, 356 }; SerializationTestHelper.assertSerializationEquals( "witness/serialization/mdc.bin", event, skip, 237); }