Java Code Examples for org.apache.log4j.spi.LoggingEvent#getMDC()

The following examples show how to use org.apache.log4j.spi.LoggingEvent#getMDC() . 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: AuditLayout.java    From knox with Apache License 2.0 6 votes vote down vote up
@Override
public String format( LoggingEvent event ) {
  sb.setLength( 0 );
  dateFormat( sb, event );
  CorrelationContext cc = (CorrelationContext)event.getMDC( Log4jCorrelationService.MDC_CORRELATION_CONTEXT_KEY );
  AuditContext ac = (AuditContext)event.getMDC( Log4jAuditService.MDC_AUDIT_CONTEXT_KEY );
  appendParameter( cc == null ? null : cc.getRootRequestId() );
  appendParameter( cc == null ? null : cc.getParentRequestId() );
  appendParameter( cc == null ? null : cc.getRequestId() );
  appendParameter( event.getLoggerName() );
  appendParameter( ac == null ? null : ac.getRemoteIp() );
  appendParameter( ac == null ? null : ac.getTargetServiceName() );
  appendParameter( ac == null ? null : ac.getUsername() );
  appendParameter( ac == null ? null : ac.getProxyUsername() );
  appendParameter( ac == null ? null : ac.getSystemUsername() );
  appendParameter( (String)event.getMDC( AuditConstants.MDC_ACTION_KEY ) );
  appendParameter( (String)event.getMDC( AuditConstants.MDC_RESOURCE_TYPE_KEY ) );
  appendParameter( (String)event.getMDC( AuditConstants.MDC_RESOURCE_NAME_KEY ) );
  appendParameter( (String)event.getMDC( AuditConstants.MDC_OUTCOME_KEY ) );
  String message = event.getRenderedMessage();
  sb.append( message == null ? "" : message ).append( LINE_SEP );
  return sb.toString();
}
 
Example 2
Source File: AuditLoggingTest.java    From knox with Apache License 2.0 6 votes vote down vote up
private void verifyAuditEvent( LoggingEvent event, String resourceName,
    String resourceType, String action, String outcome, String targetService,
    String message ) {
  event.getMDCCopy();
  CorrelationContext cc = (CorrelationContext) event.getMDC( Log4jCorrelationService.MDC_CORRELATION_CONTEXT_KEY );
  assertThat( cc, notNullValue() );
  assertThat( cc.getRequestId(), is( notNullValue() ) );
  AuditContext ac = (AuditContext) event.getMDC( Log4jAuditService.MDC_AUDIT_CONTEXT_KEY );
  assertThat( ac, notNullValue() );
  assertThat( ac.getRemoteIp(), is( ADDRESS ) );
  assertThat( ac.getRemoteHostname(), is( HOST ) );
  assertThat(event.getMDC( AuditConstants.MDC_SERVICE_KEY ), is( AuditConstants.KNOX_SERVICE_NAME ) );
  assertThat(event.getMDC( AuditConstants.MDC_COMPONENT_KEY ), is( AuditConstants.KNOX_COMPONENT_NAME ) );
  assertThat(event.getLoggerName(), is( AuditConstants.DEFAULT_AUDITOR_NAME ) );
  verifyValue( (String) event.getMDC( AuditConstants.MDC_RESOURCE_NAME_KEY ), resourceName );
  verifyValue( (String) event.getMDC( AuditConstants.MDC_RESOURCE_TYPE_KEY ), resourceType );
  verifyValue( (String) event.getMDC( AuditConstants.MDC_ACTION_KEY ), action );
  verifyValue( (String) event.getMDC( AuditConstants.MDC_OUTCOME_KEY ), outcome );
  verifyValue( ac.getTargetServiceName(), targetService );
  verifyValue( event.getRenderedMessage(), message );
}
 
Example 3
Source File: PatternParser.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public
   String convert(LoggingEvent event) {
     Object val = event.getMDC(key);
     if(val == null) {
return null;
     } else {
return val.toString();
     }
   }
 
Example 4
Source File: RequestAppender.java    From webdsl with Apache License 2.0 5 votes vote down vote up
public void append(LoggingEvent event) {
    String rle = (String)event.getMDC("request");
    if(logMap.containsKey(rle))
    {
    	logMap.get(rle).append(event);
    }
}
 
Example 5
Source File: AuditServiceTest.java    From knox with Apache License 2.0 5 votes vote down vote up
private void checkLogEventContexts( LoggingEvent event, CorrelationContext expectedCorrelationContext, AuditContext expectedAuditContext ) {
  AuditContext context = (AuditContext) event.getMDC( Log4jAuditService.MDC_AUDIT_CONTEXT_KEY );
  assertThat( context.getUsername(), is( expectedAuditContext.getUsername() ) );
  assertThat( context.getProxyUsername(), is( expectedAuditContext.getProxyUsername() ) );
  assertThat( context.getSystemUsername(), is( expectedAuditContext.getSystemUsername() ) );
  assertThat( context.getRemoteIp(), is( expectedAuditContext.getRemoteIp() ) );
  assertThat( context.getRemoteHostname(), is( expectedAuditContext.getRemoteHostname() ) );
  assertThat( context.getTargetServiceName(), is( expectedAuditContext.getTargetServiceName() ) );

  CorrelationContext correlationContext = (CorrelationContext)event.getMDC( Log4jCorrelationService.MDC_CORRELATION_CONTEXT_KEY );
  assertThat( correlationContext.getRequestId(), is( expectedCorrelationContext.getRequestId() ) );
  assertThat( correlationContext.getRootRequestId(), is( expectedCorrelationContext.getRootRequestId() ) );
  assertThat( correlationContext.getParentRequestId(), is( expectedCorrelationContext.getParentRequestId() ) );
}
 
Example 6
Source File: PrimitiveAuthorityProxy.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public int decide(LoggingEvent event) {
	Object oRunId = event.getMDC(LogUtils.MDC_RUNID_KEY);
	if (!(oRunId instanceof Long))
		return Filter.DENY;
	Long rId = (Long)oRunId;
	if (this.runId != rId.longValue())
		return Filter.DENY;
	else {
		if (event.getLevel().isGreaterOrEqual(logLevel))
			return Filter.ACCEPT;
		else
			return Filter.DENY;
	}
}
 
Example 7
Source File: AuditLoggingTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Test
public void testNoFiltersAudit() throws Exception {
  FilterConfig config = EasyMock.createNiceMock( FilterConfig.class );
  EasyMock.replay( config );

  HttpServletRequest request = EasyMock.createNiceMock( HttpServletRequest.class );
  ServletContext context = EasyMock.createNiceMock( ServletContext.class );
  GatewayConfig gatewayConfig = EasyMock.createNiceMock( GatewayConfig.class );
  EasyMock.expect( request.getMethod() ).andReturn( METHOD ).anyTimes();
  EasyMock.expect( request.getPathInfo() ).andReturn( PATH ).anyTimes();
  EasyMock.expect( request.getContextPath() ).andReturn( CONTEXT_PATH ).anyTimes();
  EasyMock.expect( request.getRemoteAddr() ).andReturn( ADDRESS ).anyTimes();
  EasyMock.expect( request.getRemoteHost() ).andReturn( HOST ).anyTimes();
  EasyMock.expect( request.getServletContext() ).andReturn( context ).anyTimes();
  EasyMock.expect( context.getAttribute(
      GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE)).andReturn(gatewayConfig).anyTimes();
  EasyMock.expect(gatewayConfig.getHeaderNameForRemoteAddress()).andReturn(
      "Custom-Forwarded-For").anyTimes();
  EasyMock.replay( request );
  EasyMock.replay( context );
  EasyMock.replay( gatewayConfig );

  HttpServletResponse response = EasyMock.createNiceMock( HttpServletResponse.class );
  EasyMock.replay( response );

  FilterChain chain = EasyMock.createNiceMock( FilterChain.class );
  EasyMock.replay( chain );

  Random rnd = ThreadLocalRandom.current();

  // Make number of total requests between 1-100
  int numberTotalRequests = rnd.nextInt(99) + 1;
  Set<Callable<Void>> callables = new HashSet<>(numberTotalRequests);
  for (int i = 0; i < numberTotalRequests; i++) {
    callables.add(() -> {
      GatewayFilter gateway = new GatewayFilter();
      gateway.init( config );
      gateway.doFilter( request, response, chain );
      gateway.destroy();
      return null;
    });
  }

  // Make number of concurrent requests between 1-10
  int numberConcurrentRequests = rnd.nextInt( 9) + 1;

  LOG.info("Executing %d total requests with %d concurrently", numberTotalRequests, numberConcurrentRequests);

  ExecutorService executor = Executors.newFixedThreadPool(numberConcurrentRequests);
  executor.invokeAll(callables);
  executor.shutdown();
  executor.awaitTermination(5, TimeUnit.SECONDS);
  assertThat(executor.isTerminated(), is(true));

  assertThat( CollectAppender.queue.size(), is( numberTotalRequests ) );

  // Use a set to make sure to dedupe any requestIds to get only unique ones
  Set<String> requestIds = new HashSet<>();
  for (LoggingEvent accessEvent : CollectAppender.queue) {
    verifyAuditEvent( accessEvent, CONTEXT_PATH + PATH, ResourceType.URI, Action.ACCESS, ActionOutcome.UNAVAILABLE, null, "Request method: GET" );

    CorrelationContext cc = (CorrelationContext)accessEvent.getMDC( Log4jCorrelationService.MDC_CORRELATION_CONTEXT_KEY );
    // There are some events that do not have a CorrelationContext associated (ie: deploy)
    if(cc != null) {
      requestIds.add(cc.getRequestId());
    }
  }

  // There should be a unique correlation id for each request
  assertThat(requestIds.size(), is(numberTotalRequests));
}
 
Example 8
Source File: GatewayCorrelationIdTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Test
public void testTestService() throws Exception {
  LOG_ENTER();
  String username = "guest";
  String password = "guest-password";
  String serviceUrl = clusterUrl + "/test-service-path/test-service-resource";

  // Make number of total requests between 1-100
  int numberTotalRequests = ThreadLocalRandom.current().nextInt(99) + 1;
  Set<Callable<Void>> callables = new HashSet<>(numberTotalRequests);
  for (int i = 0; i < numberTotalRequests; i++) {
    callables.add(() -> {
      given()
          .auth().preemptive().basic( username, password )
          .then()
          .statusCode( HttpStatus.SC_OK )
          .contentType( "text/plain" )
          .body( is( "test-service-response" ) )
          .when().get( serviceUrl );
      return null;
    });
  }

  // Make number of concurrent requests between 1-10
  int numberConcurrentRequests = ThreadLocalRandom.current().nextInt( 9) + 1;

  LOG.info("Executing {} total requests with {} concurrently",
      numberTotalRequests, numberConcurrentRequests);

  ExecutorService executor = Executors.newFixedThreadPool(numberConcurrentRequests);
  executor.invokeAll(callables);
  executor.shutdown();
  executor.awaitTermination(5, TimeUnit.SECONDS);
  assertThat(executor.isTerminated(), is(true));

  // Use a set to make sure to dedupe any requestIds to get only unique ones
  Set<String> requestIds = new HashSet<>();
  for (LoggingEvent accessEvent : CollectAppender.queue) {
    CorrelationContext cc = (CorrelationContext)accessEvent.getMDC( Log4jCorrelationService.MDC_CORRELATION_CONTEXT_KEY );
    // There are some events that do not have a CorrelationContext associated (ie: deploy)
    if(cc != null) {
      requestIds.add(cc.getRequestId());
    }
  }

  // There should be a unique correlation id for each request
  assertThat(requestIds.size(), is(numberTotalRequests));

  LOG_EXIT();
}