Skip to content

Commit

Permalink
🐛 Fix replace sentry options
Browse files Browse the repository at this point in the history
try to collect  transaction info, user information,.. etc
  • Loading branch information
miiiinju1 committed Jan 25, 2024
1 parent 360fe73 commit cbd2c57
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 86 deletions.
106 changes: 38 additions & 68 deletions src/main/java/swm_nm/morandi/aop/logging/LoggingAspect.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package swm_nm.morandi.aop.logging;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.sentry.Scope;
import io.sentry.Sentry;
import io.sentry.*;
import io.sentry.protocol.User;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
Expand All @@ -11,12 +10,10 @@
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import swm_nm.morandi.config.filter.CachedBodyHttpServletWrapper;
import swm_nm.morandi.global.utils.SecurityUtils;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.net.InetAddress;
Expand All @@ -28,19 +25,10 @@
@Slf4j
public class LoggingAspect {
private ObjectMapper mapper = new ObjectMapper();
private String host;
private String ip;

@Autowired
private EntityManager em;

@PostConstruct
public void init() throws UnknownHostException {
InetAddress addr = InetAddress.getLocalHost();
this.host = addr.getHostName();
this.ip = addr.getHostAddress();
}

//SQL 성능 측정 시 해당 메서드에 @Logging 어노테이션 붙여서 사용
@Pointcut("@annotation(swm_nm.morandi.aop.annotation.Logging)")
public void loggingPointcut() {
Expand Down Expand Up @@ -68,77 +56,59 @@ public Object controllerAroundLogging(ProceedingJoinPoint pjp) throws Throwable
} catch (Exception e) {
user.setUsername("before Login User");
}
user.setIpAddress(request.getRemoteAddr());
user.setIpAddress("{{auto}}");

//Sentry 식별 사용자 정보 등록
Sentry.setUser(user);

String callFunction = pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName();
String msg = String.format("[hostname]: %s, [hostIP]: %s, [clientIP]: %s, [clientURL]: %s ",
host, ip,
request.getRemoteAddr(),
request.getRequestURL().toString()
);


//GET 요청이 아닌 경우 Request Body를 로깅하기 위해 HttpServletRequestWrapper를 사용한다.
//이 때, HttpServletRequestWrapper는 Request Body를 한 번 읽으면 다시 읽을 수 없기 때문에
//읽은 내용을 저장해두고 다시 읽을 수 있도록 한다.
//Content-Type이 application/json인 경우에만 Request Body를 로깅한다.
if (!request.getMethod().equalsIgnoreCase("GET")&&request.getContentType() != null && request.getContentType().contains("application/json")) {

StringBuilder requestBody = new StringBuilder();
String line;
BufferedReader reader = request.getReader();

//BufferedReader를 이용해 Request Body를 읽는다.
while ((line = reader.readLine()) != null)
requestBody.append(line);

log.info("[REQUEST], [{}]: {}, [RequestBody]: {},[Parameter]: {}, {}", callFunction,request.getMethod(),
requestBody
, mapper.writeValueAsString(request.getParameterMap())
, msg);
}
//GET 요청의 경우 Parameter를 로깅한다.
else {
log.info("[REQUEST], [callFunction]: {}, [parameter]: {}, {}", callFunction
, mapper.writeValueAsString(request.getParameterMap())
, msg);
}
Breadcrumb requestBreadcrumb = new Breadcrumb();
requestBreadcrumb.setData("url", request.getRequestURL().toString());
requestBreadcrumb.setData("method", request.getMethod());
Sentry.addBreadcrumb(requestBreadcrumb);

String callFunction = pjp.getSignature().getName();


if (!request.getMethod().equalsIgnoreCase("GET") && request.getContentType() != null && request.getContentType().contains("application/json")) {
StringBuilder requestBody = new StringBuilder();
String line;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
requestBody.append(line);
}
Breadcrumb bodyBreadcrumb = new Breadcrumb();
bodyBreadcrumb.setData("body", requestBody.toString());
Sentry.addBreadcrumb(bodyBreadcrumb);
} else {
Breadcrumb paramBreadcrumb = new Breadcrumb();
paramBreadcrumb.setData("parameters", request.getParameterMap());
Sentry.addBreadcrumb(paramBreadcrumb);
}

Object result = "";
ITransaction transaction = Sentry.startTransaction(pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName(), "http");
try {
result = pjp.proceed();
transaction.setStatus(SpanStatus.OK);
return result;
}
catch (Exception e) {
transaction.setThrowable(e);
transaction.setStatus(SpanStatus.INTERNAL_ERROR);
log.error("An error occurred: {}", e.getMessage());
throw e;
}
finally {
log.info("[RESPONSE] [callFunction]: {}, [parameter]: {}, {}", callFunction,
mapper.writeValueAsString(result),
msg);
log.info("{}, \"return\": {}", callFunction,
mapper.writeValueAsString(result)
);

Sentry.configureScope(Scope::clear);

Sentry.clearBreadcrumbs();
}

}

//
//
// @Before("pointCut()")
// public void before(JoinPoint jp)
// {
//
//
// log.info("Calling method: [{}] in class: [{}]", jp.getSignature().getName(), jp.getTarget().getClass().toString());
//
// }
//
// @After("pointCut()")
// public void after(JoinPoint jp)
// {
// log.info("Exiting method: [{}] in class: [{}]", jp.getSignature().getName(), jp.getTarget().getClass().toString());
//
// }
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,41 +28,37 @@ public class GoogleService implements OAuthService{
private final ObjectMapper objectMapper;

@Value("${oauth.google.client-id}")
private String google_client_id;
private String googleClientId;

@Value("${oauth.google.client-secret}")
private String google_client_secret;
private String googleClientSecret;

@Value("${oauth.google.redirect-uri}")
private String google_client_redirect_uri;


private String googleClientRedirectUri;
//키 값
@Override
public String getType() {
return "google";
}

@Override
public String getAccessToken(String authorization_code, Boolean isDev){
public String getAccessToken(String authorizationCode, Boolean isDev){

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("code", authorization_code);
params.add("client_id", google_client_id);
params.add("client_secret", google_client_secret);
params.add("code", authorizationCode);
params.add("client_id", googleClientId);
params.add("client_secret", googleClientSecret);
params.add("grant_type", "authorization_code");
if(isDev)
params.add("redirect_uri", google_client_redirect_uri+"/dev");
params.add("redirect_uri", googleClientRedirectUri+"/dev");
else
params.add("redirect_uri", google_client_redirect_uri);

params.add("redirect_uri", googleClientRedirectUri);

HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);


//오류 발생 시 Response Entity 반환하려면 어쩔 수 없이 아래처럼 초기화 해야 함
ResponseEntity<String> responseEntity=null;
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ public class LoginService {
private final OAuthServiceFactory oAuthServiceFactory;
private final MemberLoginService memberService;

public TokenDto login(String type, String authorization_code, Boolean isDev){
public TokenDto login(String type, String authorizationCode, Boolean isDev){

OAuthService oAuthService = oAuthServiceFactory.getServiceByType(type);
if (oAuthService == null) {
throw new MorandiException(AuthErrorCode.INVALID_SOCIAL_TYPE);
}
String accessToken = oAuthService.getAccessToken(authorization_code, isDev);
String accessToken = oAuthService.getAccessToken(authorizationCode, isDev);
UserDto userDto = oAuthService.getMemberInfo(accessToken);

return memberService.loginOrRegisterMember(userDto);
Expand All @@ -36,7 +36,7 @@ public TokenDto OAuthJoinOrLogin(String type, String accessToken){
throw new MorandiException(AuthErrorCode.INVALID_SOCIAL_TYPE);
}
UserDto userDto = oAuthService.getMemberInfo(accessToken);

return memberService.loginOrRegisterMember(userDto);


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

public interface OAuthService {
String getType();
String getAccessToken(String authorization_code, Boolean isDev);
String getAccessToken(String authorizationCode, Boolean isDev);
UserDto getMemberInfo(String accessToken);

// String getAccessTokenDev(String authorization_code);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("OnlineJudge 쿠키 존재");
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}

Expand Down

0 comments on commit cbd2c57

Please sign in to comment.