Skip to content

Commit

Permalink
feat - #160 slack api 사용과 메세지 구성하는 메소드 분리
Browse files Browse the repository at this point in the history
  • Loading branch information
jumining committed Aug 20, 2024
1 parent b1d5ba5 commit 9c416cb
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 72 deletions.
73 changes: 1 addition & 72 deletions src/main/java/sopt/org/hmh/domain/slack/SlackSender.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,12 @@

import com.slack.api.Slack;
import com.slack.api.model.Attachment;
import com.slack.api.model.Field;
import com.slack.api.webhook.WebhookPayloads;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sopt.org.hmh.domain.user.repository.UserRepository;
import sopt.org.hmh.global.common.exception.base.ExceptionBase;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
Expand All @@ -23,27 +16,8 @@
public class SlackSender {

private final Slack slackClient = Slack.getInstance();
private final UserRepository userRepository;

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

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

public void sendNotificationNewUser(String userName, String os) {
sendSlackNotification(newUserWebUrl, "🎉 신규 유저 회원 가입 발생", generateNewUserSlackAttachment(userName, os));
}

public void sendNotificationServerInternalError(Exception e, HttpServletRequest request) {
sendSlackNotification(serverErrorWebUrl, "🚨 서버 내부 에러 발생", generateInternalErrorSlackAttachment(e, request));
}

public void sendNotificationServerRuntimeException(ExceptionBase e, HttpServletRequest request) {
sendSlackNotification(serverErrorWebUrl, "😭 서버 오류 발생", generateRuntimeExceptionSlackAttachment(e, request));
}

private void sendSlackNotification(String webhookUrl, String title, Attachment attachment) {
public void sendSlackNotification(String webhookUrl, String title, Attachment attachment) {
try {
slackClient.send(webhookUrl, WebhookPayloads.payload(p -> p
.text(title)
Expand All @@ -53,49 +27,4 @@ private void sendSlackNotification(String webhookUrl, String title, Attachment a
log.debug("Slack 통신 예외 발생: {}", slackError.getMessage());
}
}

private Attachment generateNewUserSlackAttachment(String userName, String os) {
return Attachment.builder()
.color("98ff98") // 초록색
.title("새로운 유저 '" + userName + "'님이 가입했습니다!")
.fields(List.of(
generateSlackField("총 유저 수", " 👉 " + userRepository.count() + "명"),
generateSlackField("가입한 OS", "👉 " + os)))
.build();
}

private Attachment generateInternalErrorSlackAttachment(Exception e, HttpServletRequest request) {
String requestTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").format(LocalDateTime.now());
return Attachment.builder()
.color("ff0000") // 붉은색
.title(requestTime + " 발생 오류 로그")
.fields(List.of(
generateSlackField("User Info", "- ID : " + request.getRemoteUser()
+ " \n- IP : " + request.getRemoteAddr()),
generateSlackField("Request URL", request.getRequestURI() + " [" + request.getMethod()+"]"),
generateSlackField("Error Message", "[500] " + e.getMessage())))
.build();
}

private Attachment generateRuntimeExceptionSlackAttachment(ExceptionBase e, HttpServletRequest request) {
String requestTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").format(LocalDateTime.now());
return Attachment.builder()
.color("ffb700") // 주황색
.title(requestTime + " 발생 오류 로그")
.fields(List.of(
generateSlackField("User Info", "- ID : " + request.getRemoteUser()
+ " \n- IP : " + request.getRemoteAddr()
+ " \n- TOKEN: " + request.getHeader("Authorization")),
generateSlackField("Request URL", "[" + request.getMethod()+"] " + request.getRequestURI()),
generateSlackField("Error Info", "[" + e.getError().getHttpStatusCode() + "] " + e.getMessage())))
.build();
}

private Field generateSlackField(String title, String value) {
return Field.builder()
.title(title)
.value(value)
.valueShortEnough(false)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package sopt.org.hmh.domain.slack.provider;

import com.slack.api.model.Attachment;
import com.slack.api.model.Field;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sopt.org.hmh.domain.slack.SlackSender;
import sopt.org.hmh.domain.slack.constant.SlackStatus;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
@RequiredArgsConstructor
public class SlackErrorNotificationProvider {

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

private final SlackSender slackSender;

public void sendNotification(SlackStatus status, Exception e, HttpServletRequest request) {
slackSender.sendSlackNotification(serverErrorWebUrl, status.getTitle(),
generateErrorSlackAttachment(e, request, status.getColor()));
}

private Attachment generateErrorSlackAttachment(Exception e, HttpServletRequest request, String colorCode) {
String requestTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").format(LocalDateTime.now());
return Attachment.builder()
.color(colorCode)
.title(requestTime + " 발생 오류 로그")
.fields(List.of(
generateSlackField("User Info", "- ID : " + request.getRemoteUser()),
generateSlackField("Request URL", "[" + request.getMethod()+"] " + request.getRequestURI()),
generateSlackField("Error Info", e.getMessage())))
.build();
}

private Field generateSlackField(String title, String value) {
return Field.builder()
.title(title)
.value(value)
.valueShortEnough(false)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package sopt.org.hmh.domain.slack.provider;

import com.slack.api.model.Attachment;
import com.slack.api.model.Field;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sopt.org.hmh.domain.slack.SlackSender;
import sopt.org.hmh.domain.slack.constant.SlackStatus;
import sopt.org.hmh.domain.user.repository.UserRepository;

import java.util.List;

@Component
@RequiredArgsConstructor
public class SlackNewUserNotificationProvider {

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

private final SlackSender slackSender;
private final UserRepository userRepository;

public void sendNotification(String userName, String os, SlackStatus status) {
slackSender.sendSlackNotification(newUserWebUrl, status.getTitle(),
generateNewUserSlackAttachment(userName, os, status.getColor()));
}

public Attachment generateNewUserSlackAttachment(String userName, String os, String colorCode) {
return Attachment.builder()
.color(colorCode)
.title("새로운 유저 '" + userName + "'님이 가입했습니다!")
.fields(List.of(
generateSlackField("총 유저 수", " 👉 " + userRepository.count() + "명"),
generateSlackField("가입한 OS", "👉 " + os)))
.build();
}

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

0 comments on commit 9c416cb

Please sign in to comment.