Java Code Examples for org.apache.logging.log4j.Marker

The following examples show how to use org.apache.logging.log4j.Marker. These examples are extracted from open source projects. 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 Project: xyz-hub   Author: heremaps   File: XYZHubRESTVerticle.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates and sends an error response to the client.
 */
public static void sendErrorResponse(final RoutingContext context, final Throwable exception) {
  ErrorMessage error;

  try {
    final Marker marker = Api.Context.getMarker(context);

    error = new ErrorMessage(context, exception);
    if (error.statusCode == 500) {
      error.message = null;
      logger.error(marker, "Sending error response: {} {} {}", error.statusCode, error.reasonPhrase, exception);
    }
    else {
      logger.warn(marker, "Sending error response: {} {} {}", error.statusCode, error.reasonPhrase, exception);
    }
  } catch (Exception e) {
    logger.error("Error {} while preparing error response {}", e, exception);
    error = new ErrorMessage();
  }

  context.response()
      .putHeader(CONTENT_TYPE, APPLICATION_JSON)
      .setStatusCode(error.statusCode)
      .setStatusMessage(error.reasonPhrase)
      .end(Json.encode(error));
}
 
Example #2
Source Project: logging-log4j2   Author: apache   File: SLF4JLogger.java    License: Apache License 2.0 6 votes vote down vote up
private org.slf4j.Marker getMarker(final Marker marker) {
    if (marker == null) {
        return null;
    }
    final org.slf4j.Marker slf4jMarker = MarkerFactory.getMarker(marker.getName());
    final Marker[] parents = marker.getParents();
    if (parents != null) {
        for (final Marker parent : parents) {
            final org.slf4j.Marker slf4jParent = getMarker(parent);
            if (!slf4jMarker.contains(slf4jParent)) {
                slf4jMarker.add(slf4jParent);
            }
        }
    }
    return slf4jMarker;
}
 
Example #3
Source Project: logging-log4j2   Author: apache   File: RingBufferLogEventTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetLevelReturnsOffIfNullLevelSet() {
    final RingBufferLogEvent evt = new RingBufferLogEvent();
    final String loggerName = null;
    final Marker marker = null;
    final String fqcn = null;
    final Level level = null;
    final Message data = null;
    final Throwable t = null;
    final ContextStack contextStack = null;
    final String threadName = null;
    final StackTraceElement location = null;
    evt.setValues(null, loggerName, marker, fqcn, level, data, t, (StringMap) evt.getContextData(),
            contextStack, -1, threadName, -1, location, new FixedPreciseClock(), new DummyNanoClock(1));
    assertEquals(Level.OFF, evt.getLevel());
}
 
Example #4
Source Project: logging-log4j2   Author: apache   File: MarkerAttributeConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testConvert01() {
    final Marker marker = MarkerManager.getMarker("testConvert01");

    final String converted = this.converter.convertToDatabaseColumn(marker);

    assertNotNull("The converted value should not be null.", converted);
    assertEquals("The converted value is not correct.", "testConvert01", converted);

    final Marker reversed = this.converter.convertToEntityAttribute(converted);

    assertNotNull("The reversed value should not be null.", reversed);
    assertEquals("The reversed value is not correct.", "testConvert01", marker.getName());
}
 
Example #5
Source Project: logging-log4j2   Author: apache   File: AbstractLogger.java    License: Apache License 2.0 6 votes vote down vote up
@PerformanceSensitive
// NOTE: This is a hot method. Current implementation compiles to 27 bytes of byte code.
// This is within the 35 byte MaxInlineSize threshold. Modify with care!
private void tryLogMessage(final String fqcn,
                           final StackTraceElement location,
                           final Level level,
                           final Marker marker,
                           final Message msg,
                           final Throwable throwable) {
    try {
        log(level, marker, fqcn, location, msg, throwable);
    } catch (final Exception e) {
        // LOG4J2-1990 Log4j2 suppresses all exceptions that occur once application called the logger
        handleLogMessageException(e, fqcn, msg);
    }
}
 
Example #6
Source Project: xyz-hub   Author: heremaps   File: RemoteFunctionClient.java    License: Apache License 2.0 6 votes vote down vote up
private void enqueue(final Marker marker, byte[] bytes, boolean fireAndForget, final Handler<AsyncResult<byte[]>> callback) {
  FunctionCall fc = new FunctionCall(marker, bytes, fireAndForget, callback);

  /*if (Service.currentTimeMillis() > lastSizeAdjustment.get() + SIZE_ADJUSTMENT_INTERVAL
      && fc.getByteSize() + queue.getByteSize() > queue.getMaxByteSize()) {
    //Element won't fit into queue so we try to enlarge it
    adjustQueueByteSizes();
  }*/

  //In any case add the element to the queue
  queue.add(fc)
      //Send timeout for discarded (old) calls
      .forEach(timeoutFc ->
          timeoutFc.callback
              .handle(Future.failedFuture(new HttpException(TOO_MANY_REQUESTS, "Remote function is busy or cannot be invoked."))));
}
 
Example #7
Source Project: logging-log4j2   Author: apache   File: XmlSetupContextInitializer.java    License: Apache License 2.0 6 votes vote down vote up
public void setupModule(final SetupContext context, final boolean includeStacktrace,
        final boolean stacktraceAsString) {
    // JRE classes: we cannot edit those with Jackson annotations
    context.setMixInAnnotations(StackTraceElement.class, StackTraceElementXmlMixIn.class);
    // Log4j API classes: we do not want to edit those with Jackson annotations because the API module should not
    // depend on Jackson.
    context.setMixInAnnotations(Marker.class, MarkerXmlMixIn.class);
    context.setMixInAnnotations(Level.class, LevelMixIn.class);
    context.setMixInAnnotations(Instant.class, InstantXmlMixIn.class);
    context.setMixInAnnotations(LogEvent.class, LogEventWithContextListXmlMixIn.class);
    // Log4j Core classes: we do not want to bring in Jackson at runtime if we do not have to.
    context.setMixInAnnotations(ExtendedStackTraceElement.class, ExtendedStackTraceElementXmlMixIn.class);
    context.setMixInAnnotations(ThrowableProxy.class, includeStacktrace
            ? (stacktraceAsString ? ThrowableProxyWithStacktraceAsStringXmlMixIn.class : ThrowableProxyXmlMixIn.class)
            : ThrowableProxyWithoutStacktraceXmlMixIn.class);
}
 
Example #8
Source Project: logging-log4j2   Author: apache   File: StringMatchFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
        final Object p0, final Object p1, final Object p2, final Object p3,
        final Object p4, final Object p5, final Object p6,
        final Object p7) {
    return filter(logger.getMessageFactory().newMessage(msg, p0, p1, p2, p3, p4, p5, p6, p7).getFormattedMessage());
}
 
Example #9
Source Project: logging-log4j2   Author: apache   File: ThresholdFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
        final Object p0, final Object p1, final Object p2, final Object p3,
        final Object p4, final Object p5, final Object p6,
        final Object p7) {
    return filter(level);
}
 
Example #10
Source Project: logging-log4j2   Author: apache   File: MapFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
        final Object p0, final Object p1, final Object p2, final Object p3,
        final Object p4, final Object p5, final Object p6,
        final Object p7, final Object p8) {
    return Result.NEUTRAL;
}
 
Example #11
Source Project: logging-log4j2   Author: apache   File: MarkerFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
        final Object p0, final Object p1, final Object p2, final Object p3,
        final Object p4, final Object p5, final Object p6,
        final Object p7) {
    return filter(marker);
}
 
Example #12
Source Project: xyz-hub   Author: heremaps   File: DynamoConnectorConfigClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void getAllConnectors(Marker marker, Handler<AsyncResult<List<Connector>>> handler) {
  final List<Connector> result = new ArrayList<>();
  try {
    connectors.scan().pages().forEach(p -> p.forEach(i -> {
      final Connector connector = Json.decodeValue(i.toJSON(), Connector.class);
      result.add(connector);
    }));
    handler.handle(Future.succeededFuture(result));
  }
  catch (Exception e) {
    handler.handle(Future.failedFuture(new RuntimeException("Error retrieving all connectors.", e)));
  }
}
 
Example #13
Source Project: xyz-hub   Author: heremaps   File: InMemSpaceConfigClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void storeSpace(Marker marker, Space space, Handler<AsyncResult<Space>> handler) {
  if (space.getId() == null) {
    space.setId(RandomStringUtils.randomAlphanumeric(10));
  }
  spaceMap.put(space.getId(), space);
  handler.handle(Future.succeededFuture(space));
}
 
Example #14
Source Project: glowroot   Author: glowroot   File: Log4j2xMarkerIT.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() {
    logger.debug((Marker) null, "bcd_t", new IllegalStateException("234"));
    logger.info((Marker) null, "cde_t", new IllegalStateException("345"));
    logger.warn((Marker) null, "def_t", new IllegalStateException("456"));
    logger.error((Marker) null, "efg_t", new IllegalStateException("567"));
}
 
Example #15
Source Project: logging-log4j2   Author: apache   File: ScriptFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final Message msg,
                     final Throwable t) {
    final SimpleBindings bindings = new SimpleBindings();
    bindings.put("logger", logger);
    bindings.put("level", level);
    bindings.put("marker", marker);
    bindings.put("message", msg);
    bindings.put("parameters", null);
    bindings.put("throwable", t);
    bindings.putAll(configuration.getProperties());
    bindings.put("substitutor", configuration.getStrSubstitutor());
    final Object object = configuration.getScriptManager().execute(script.getName(), bindings);
    return object == null || !Boolean.TRUE.equals(object) ? onMismatch : onMatch;
}
 
Example #16
Source Project: xyz-hub   Author: heremaps   File: SpaceConfigClient.java    License: Apache License 2.0 5 votes vote down vote up
public void delete(Marker marker, String spaceId, Handler<AsyncResult<Space>> handler) {
  deleteSpace(marker, spaceId, ar -> {
    if (ar.succeeded()) {
      invalidateCache(spaceId);
      logger.info(marker, "space[{}]: Deleted space", spaceId);
      handler.handle(Future.succeededFuture(ar.result()));
    } else {
      logger.error(marker, "space[{}]: Failed deleting the space", spaceId, ar.cause());
      handler.handle(Future.failedFuture(ar.cause()));
    }
  });
}
 
Example #17
Source Project: logging-log4j2   Author: apache   File: BurstFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
        final Object p0, final Object p1, final Object p2, final Object p3,
        final Object p4, final Object p5, final Object p6,
        final Object p7, final Object p8, final Object p9) {
    return filter(level);
}
 
Example #18
Source Project: logging-log4j2   Author: apache   File: LevelMatchFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
        final Object p0, final Object p1, final Object p2, final Object p3,
        final Object p4, final Object p5, final Object p6,
        final Object p7, final Object p8, final Object p9) {
    return filter(level);
}
 
Example #19
Source Project: logging-log4j2   Author: apache   File: BurstFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
        final Object p0, final Object p1, final Object p2, final Object p3,
        final Object p4, final Object p5, final Object p6,
        final Object p7, final Object p8) {
    return filter(level);
}
 
Example #20
Source Project: xyz-hub   Author: heremaps   File: LambdaFunctionClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Invokes the remote lambda function and returns the decompressed response as bytes.
 */
@Override
protected void invoke(final Marker marker, byte[] bytes, boolean fireAndForget, final Handler<AsyncResult<byte[]>> callback) {
  final RemoteFunctionConfig remoteFunction = getConnectorConfig().remoteFunction;
  logger.debug(marker, "Invoking remote lambda function with id '{}' Event size is: {}", remoteFunction.id, bytes.length);

  InvokeRequest invokeReq = new InvokeRequest()
      .withFunctionName(((AWSLambda) remoteFunction).lambdaARN)
      .withPayload(ByteBuffer.wrap(bytes))
      .withInvocationType(fireAndForget ? InvocationType.Event : InvocationType.RequestResponse);

  asyncClient.invokeAsync(invokeReq, new AsyncHandler<InvokeRequest, InvokeResult>() {
    @Override
    public void onError(Exception exception) {
      if (callback == null) {
        logger.error(marker, "Error sending event to remote lambda function", exception);
      }
      else {
        callback.handle(Future.failedFuture(getWHttpException(marker, exception)));
      }
    }

    @Override
    public void onSuccess(InvokeRequest request, InvokeResult result) {
      byte[] responseBytes = new byte[result.getPayload().remaining()];
      result.getPayload().get(responseBytes);
      callback.handle(Future.succeededFuture(responseBytes));
    }
  });
}
 
Example #21
Source Project: logging-log4j2   Author: apache   File: MapFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
        final Object p0, final Object p1, final Object p2, final Object p3,
        final Object p4, final Object p5, final Object p6,
        final Object p7, final Object p8, final Object p9) {
    return Result.NEUTRAL;
}
 
Example #22
Source Project: logging-log4j2   Author: apache   File: MarkerSimpleNamePatternConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
    final Marker marker = event.getMarker();
    if (marker != null) {
        toAppendTo.append(marker.getName());
    }
}
 
Example #23
Source Project: logging-log4j2   Author: apache   File: MapFilter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
        final Object p0) {
    return Result.NEUTRAL;
}
 
Example #24
Source Project: logging-log4j2   Author: apache   File: LevelMatchFilter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Result filter(final Logger logger, final Level level, final Marker marker, final String msg,
        final Object p0, final Object p1, final Object p2, final Object p3,
        final Object p4, final Object p5) {
    return filter(level);
}
 
Example #25
Source Project: core-ng-project   Author: neowu   File: ESLogger.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean isEnabled(Level level, Marker marker, Message data, Throwable t) {
    return isEnabled(level);
}
 
Example #26
Source Project: logging-log4j2   Author: apache   File: AbstractLogger.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void trace(final Marker marker, final String message, final Object p0, final Object p1) {
    logIfEnabled(FQCN, Level.TRACE, marker, message, p0, p1);
}
 
Example #27
Source Project: logging-log4j2   Author: apache   File: AbstractLogger.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void warn(final Marker marker, final CharSequence message) {
    logIfEnabled(FQCN, Level.WARN, marker, message, null);
}
 
Example #28
Source Project: logging-log4j2   Author: apache   File: AbstractLogger.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void trace(final Marker marker, final Object message, final Throwable t) {
    logIfEnabled(FQCN, Level.TRACE, marker, message, t);
}
 
Example #29
Source Project: xyz-hub   Author: heremaps   File: DynamoSpaceConfigClient.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void getSelectedSpaces(Marker marker, SpaceAuthorizationCondition authorizedCondition, SpaceSelectionCondition selectedCondition,
    Handler<AsyncResult<List<Space>>> handler) {
  logger.info(marker, "Getting selected spaces");

  if (authorizedCondition == null || selectedCondition == null) {
    throw new NullPointerException("authorizedCondition and selectedCondition are required");
  }

  final List<Space> result = new ArrayList<>();
  logger.debug(marker, "authorizedCondition: spaceIds: {}, ownerIds {}, packages: {}", authorizedCondition.spaceIds, authorizedCondition.ownerIds, authorizedCondition.packages);
  logger.debug(marker, "selectedCondition: spaceIds: {}, ownerIds {}, packages: {}, shared: {}, negateOwnerIds: {}", selectedCondition.spaceIds, selectedCondition.ownerIds, selectedCondition.packages, selectedCondition.shared, selectedCondition.negateOwnerIds);

  try {
    final Set<String> authorizedSpaces = getAuthorizedSpaces(marker, authorizedCondition);

    // get all shared spaces if the selection for shared spaces is enabled
    if (selectedCondition.shared) {
      spaces.getIndex("shared-index").query(new QuerySpec().withHashKey("shared", 1).withProjectionExpression("id")).pages()
          .forEach(p -> p.forEach(i -> {
            authorizedSpaces.add(i.getString("id"));
          }));
      logger.debug(marker, "Number of space IDs after addition of shared spaces: {}", authorizedSpaces.size());
    }

    // filter out the ones not present in the selectedCondition (null or empty represents 'do not filter')
    if (!CollectionUtils.isNullOrEmpty(selectedCondition.spaceIds)) {
      authorizedSpaces.removeIf(i -> !selectedCondition.spaceIds.contains(i));
      logger.debug(marker, "Number of space IDs after removal of the ones not selected by ID: {}", authorizedSpaces.size());
    }

    // now filter all spaceIds with the ones being selected in the selectedCondition (by checking the space's ownership) (
    if (!CollectionUtils.isNullOrEmpty(selectedCondition.ownerIds)) {
      final Set<String> ownersSpaces = new HashSet<>();
      selectedCondition.ownerIds.forEach(o ->
          spaces.getIndex("owner-index").query(new QuerySpec().withHashKey("owner", o).withProjectionExpression("id")).pages()
              .forEach(p -> p.forEach(i -> ownersSpaces.add(i.getString("id")))));

      // HINT: A ^ TRUE == !A (negateOwnerIds: keep or remove the spaces contained in the owner's spaces list)
      authorizedSpaces.removeIf(i -> !selectedCondition.negateOwnerIds ^ ownersSpaces.contains(i));
      logger.debug(marker, "Number of space IDs after removal of the ones not selected by owner: {}", authorizedSpaces.size());
    }

    // TODO selection per packages is not yet supported: selectedCondition.packages

    logger.info(marker, "Final number of space IDs to be retrieved from DynamoDB: {}", authorizedSpaces.size());
    if (!authorizedSpaces.isEmpty()) {
      int batches = (int) Math.ceil((double) authorizedSpaces.size()/100);
      for (int i=0; i<batches; i++) {
        final TableKeysAndAttributes keys = new TableKeysAndAttributes(dynamoClient.tableName);
        authorizedSpaces.stream().skip(i*100).limit(100).forEach(id -> keys.addHashOnlyPrimaryKey("id", id));

        BatchGetItemOutcome outcome = dynamoClient.db.batchGetItem(keys);
        processOutcome(outcome, result);

        while (!outcome.getUnprocessedKeys().isEmpty()) {
          outcome = dynamoClient.db.batchGetItemUnprocessed(outcome.getUnprocessedKeys());
          processOutcome(outcome, result);
        }
      }
    }

    logger.info(marker, "Number of spaces retrieved from DynamoDB: {}", result.size());
    handler.handle(Future.succeededFuture(result));
  } catch (AmazonDynamoDBException e) {
    logger.error(marker, "Failure getting authorized spaces", e);
    handler.handle(Future.failedFuture(e));
  }
}
 
Example #30
Source Project: Javacord   Author: Javacord   File: PrivacyProtectionLogger.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean isEnabled(Level level, Marker marker, Message message, Throwable t) {
    return delegate.isEnabled(level, marker);
}