Skip to content

Commit

Permalink
fix(logging): Add API ID into the MDC
Browse files Browse the repository at this point in the history
  • Loading branch information
tcompiegne committed Dec 11, 2020
1 parent 523465c commit 3390cad
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/main/java/io/gravitee/policy/jwt/JWTPolicy.java
Expand Up @@ -37,6 +37,7 @@
import io.vertx.core.Vertx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.core.env.Environment;

import java.util.List;
Expand Down Expand Up @@ -99,14 +100,17 @@ public void onRequest(Request request, Response response, ExecutionContext execu
// 2_ Validate the token algorithm + signature
validate(executionContext, jwt)
.whenComplete((claims, throwable) -> {
final String api = String.valueOf(executionContext.getAttribute(ATTR_API));
MDC.put("api", api);
if (throwable != null) {
if (throwable.getCause() instanceof InvalidTokenException) {
LOGGER.debug(String.format(errorMessageFormat, executionContext.getAttribute(ATTR_API), request.id(), request.path(), throwable.getMessage()), throwable.getCause());
LOGGER.debug(String.format(errorMessageFormat, api, request.id(), request.path(), throwable.getMessage()), throwable.getCause());
request.metrics().setMessage(throwable.getCause().getCause().getMessage());
} else {
LOGGER.error(String.format(errorMessageFormat, executionContext.getAttribute(ATTR_API), request.id(), request.path(), throwable.getMessage()), throwable.getCause());
LOGGER.error(String.format(errorMessageFormat, api, request.id(), request.path(), throwable.getMessage()), throwable.getCause());
request.metrics().setMessage(throwable.getCause().getMessage());
}
MDC.remove("api");
policyChain.failWith(PolicyResult.failure(
JWT_INVALID_TOKEN_KEY,
HttpStatusCode.UNAUTHORIZED_401,
Expand Down Expand Up @@ -140,16 +144,20 @@ public void onRequest(Request request, Response response, ExecutionContext execu
// Finally continue the process...
policyChain.doNext(request, response);
} catch (Exception e) {
LOGGER.error(String.format(errorMessageFormat, executionContext.getAttribute(ATTR_API), request.id(), request.path(), e.getMessage()), e.getCause());
LOGGER.error(String.format(errorMessageFormat, api, request.id(), request.path(), e.getMessage()), e.getCause());
policyChain.failWith(PolicyResult.failure(
JWT_INVALID_TOKEN_KEY,
HttpStatusCode.UNAUTHORIZED_401,
UNAUTHORIZED_MESSAGE));
} finally {
MDC.remove("api");
}
}
});
} catch (Exception e) {
MDC.put("api", String.valueOf(executionContext.getAttribute(ATTR_API)));
LOGGER.error(String.format(errorMessageFormat, executionContext.getAttribute(ATTR_API), request.id(), request.path(), e.getMessage()), e.getCause());
MDC.remove("api");
policyChain.failWith(PolicyResult.failure(
JWT_MISSING_TOKEN_KEY,
HttpStatusCode.UNAUTHORIZED_401,
Expand Down

0 comments on commit 3390cad

Please sign in to comment.