Skip to content

Commit

Permalink
Merge pull request #82 from Modagbul/fix/auth
Browse files Browse the repository at this point in the history
slack Alarm 기능 추가
  • Loading branch information
minsu20 authored Nov 20, 2023
2 parents ce88892 + ae99b7b commit 1bbf1af
Show file tree
Hide file tree
Showing 5 changed files with 105 additions and 2 deletions.
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ dependencies {
implementation platform('software.amazon.awssdk:bom:2.17.230')
implementation 'software.amazon.awssdk:s3'

//slack
implementation 'com.slack.api:slack-api-client:1.30.0'

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ public class Member extends BaseTimeEntity {
private RegistrationStatus registrationStatus;

@Convert(converter = AesConverter.class)
@Column(nullable = false)
private String email;

private String profileImage;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import com.moing.backend.domain.teamMember.domain.service.TeamMemberSaveService;
import com.moing.backend.domain.teamScore.application.mapper.TeamScoreMapper;
import com.moing.backend.domain.teamScore.domain.service.TeamScoreSaveService;
import com.moing.backend.global.util.SlackService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

Expand All @@ -26,6 +27,7 @@ public class CreateTeamUserCase {
private final TeamMapper teamMapper;
private final TeamScoreSaveService teamScoreSaveService;
private final TeamScoreMapper teamScoreMapper;
private final SlackService slackService;

public CreateTeamResponse createTeam(CreateTeamRequest createTeamRequest, String socialId){
Member member = memberGetService.getMemberBySocialId(socialId);
Expand All @@ -36,6 +38,7 @@ public CreateTeamResponse createTeam(CreateTeamRequest createTeamRequest, String
team.approveTeam();
//====지워야 함 (테스트 용)=====
teamScoreSaveService.save(teamScoreMapper.mapToTeamScore(team)); // 팀스코어 엔티티 생성
slackService.sendSlackTeamCreatedMessage(team.getName(), team.getLeaderId());
return new CreateTeamResponse(team.getTeamId());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import com.moing.backend.global.response.ErrorCode;
import com.moing.backend.global.response.ErrorResponse;
import com.moing.backend.global.util.SlackService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand All @@ -12,15 +14,18 @@
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.context.support.DefaultMessageSourceResolvable;

import javax.servlet.http.HttpServletRequest;
import java.util.function.Consumer;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
@RequiredArgsConstructor
public class GlobalExceptionHandler {

private static final String LOG_FORMAT = "Class : {}, Code : {}, Message : {}";
private final SlackService slackService;

@ExceptionHandler(ApplicationException.class)
public ResponseEntity<ErrorResponse> handleApplicationException(ApplicationException ex) {
Expand Down Expand Up @@ -51,7 +56,8 @@ public ResponseEntity<ErrorResponse> httpRequestNotSupportedExceptionHandler(Htt
}

@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> internalServerErrorHandler(Exception ex) {
public ResponseEntity<ErrorResponse> internalServerErrorHandler(Exception ex, HttpServletRequest request) {
slackService.sendSlackAlertErrorLog(ex, request);
return handleException(ex, ErrorCode.INTERNAL_SERVER_ERROR, ErrorCode.INTERNAL_SERVER_ERROR.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR, log::error);
}

Expand Down
93 changes: 93 additions & 0 deletions src/main/java/com/moing/backend/global/util/SlackService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package com.moing.backend.global.util;

import com.slack.api.Slack;
import com.slack.api.model.Attachment;
import com.slack.api.model.Field;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.slack.api.webhook.WebhookPayloads.payload;

@Service
@Slf4j
public class SlackService {

@Value("${webhook.slack.error_url}")
private String errorWebhookUrl;

@Value("${webhook.slack.team_alarm_url}")
private String teamAlarmWebhookUrl;

private final Slack slackClient = Slack.getInstance();

// 공통 슬랙 메시지 전송 메서드
@Async
public void sendSlackMessage(String webhookUrl, String message, List<Attachment> attachments) {
try {
slackClient.send(webhookUrl, payload(p -> p
.text(message)
.attachments(attachments)
));
} catch (IOException slackError) {
log.debug("Slack 통신과의 예외 발생");
}
}

// 슬랙 에러 알림 메서드
public void sendSlackAlertErrorLog(Exception e, HttpServletRequest request) {
String message = "[500 에러가 발생했습니다.]";
List<Attachment> attachments = List.of(generateSlackErrorAttachment(e, request));
sendSlackMessage(errorWebhookUrl, message, attachments);
}

// 슬랙 소모임 생성 알림 메서드
public void sendSlackTeamCreatedMessage(String teamName, Long leaderId) {
String message = String.format("새로운 소모임 '%s'이(가) 생성되었습니다!", teamName);
List<Attachment> attachments = List.of(generateSlackTeamAttachment(teamName, leaderId));
sendSlackMessage(teamAlarmWebhookUrl, message, attachments);
}

private Attachment generateSlackTeamAttachment(String teamName, Long leaderId) {
return Attachment.builder()
.color("36a64f")
.title("소모임 생성 알림")
.fields(List.of(
generateSlackField("소모임 이름", teamName),
generateSlackField("생성자 아이디", String.valueOf(leaderId))
))
.build();
}

// attachment 생성 메서드
private Attachment generateSlackErrorAttachment(Exception e, HttpServletRequest request) {
String requestTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").format(LocalDateTime.now());
String xffHeader = request.getHeader("X-FORWARDED-FOR");
return Attachment.builder()
.color("ff0000")
.title(requestTime + " 발생 에러 로그")
.fields(List.of(
generateSlackField("Request IP", xffHeader == null ? request.getRemoteAddr() : xffHeader),
generateSlackField("Request URL", request.getRequestURL() + " " + request.getMethod()),
generateSlackField("Error Message", e.getMessage())
)
)
.build();
}

private Field generateSlackField(String title, String value) {
return Field.builder()
.title(title)
.value(value)
.valueShortEnough(false)
.build();
}

}

0 comments on commit 1bbf1af

Please sign in to comment.