package ee.tuleva.onboarding.config;

import java.io.IOException;
import java.security.Principal;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

@Slf4j
@Component
public class MDCFilter extends GenericFilterBean {

  private final String PERSONAL_ID = "personalId";

  @Override
  public void destroy() {}

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    boolean successfulRegistration = false;

    HttpServletRequest req = (HttpServletRequest) request;
    Principal principal = req.getUserPrincipal();

    if (principal != null) {
      String personalId = principal.getName();
      successfulRegistration = registerPersonalId(personalId);
    }

    try {
      chain.doFilter(request, response);
    } finally {
      if (successfulRegistration) {
        MDC.remove(PERSONAL_ID);
      }
    }
  }

  private boolean registerPersonalId(String personalId) {
    if (personalId != null && personalId.trim().length() > 0) {
      MDC.put(PERSONAL_ID, personalId);
      return true;
    }
    return false;
  }
}

@@ -31,16 +31,41 @@
 onfig;%0A%0A
+import io.sentry.Sentry;%0A
 import j
@@ -1191,56 +1191,167 @@
 on) 
-%7B%0A        MDC.remove(PERSONAL_ID);%0A      %7D%0A    %7D
+clearPersonalId();%0A    %7D%0A  %7D%0A%0A  private void clearPersonalId() %7B%0A    MDC.remove(PERSONAL_ID);%0A    Sentry.configureScope(scope -%3E scope.removeTag(PERSONAL_ID));
 %0A  %7D
@@ -1470,24 +1470,101 @@
 th() %3E 0) %7B%0A
+      Sentry.configureScope(scope -%3E scope.setTag(PERSONAL_ID, personalId));%0A
       MDC.pu

Add personal id as a Sentry scope tag so its searchable