Skip to content

Commit

Permalink
Merge pull request #82 from ku-ring/refactor/log-level-change-#80
Browse files Browse the repository at this point in the history
[Refactor-#80] Log level change
  • Loading branch information
zbqmgldjfh authored Aug 30, 2023
2 parents c41af15 + 4da1c97 commit 5934043
Show file tree
Hide file tree
Showing 21 changed files with 147 additions and 104 deletions.
4 changes: 2 additions & 2 deletions scripts/start.sh
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ cp $PROJECT_ROOT/build/libs/*.jar $JAR_FILE
# jar 파일 실행
chmod 755 $JAR_FILE
echo "$TIME_NOW > $JAR_FILE 파일 실행" >> $DEPLOY_LOG
nohup java -jar $JAR_FILE > $APP_LOG 2> $ERROR_LOG &
nohup java -jar $JAR_FILE &

CURRENT_PID=$(pgrep -f $JAR_FILE)
echo "$TIME_NOW > 실행된 프로세스 아이디 $CURRENT_PID 입니다." >> $DEPLOY_LOG
echo "$TIME_NOW > 실행된 프로세스 아이디 $CURRENT_PID 입니다." >> $DEPLOY_LOG
Original file line number Diff line number Diff line change
Expand Up @@ -169,10 +169,10 @@ public ResponseDto enrollFakeNotice(@RequestBody HashMap<String, String> request
LocalDateTime now = LocalDateTime.now();
String fakeNoticePostedDate = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

log.info("fake articleId = {}", fakeNoticeArticleId);
log.info("fake postedDate = {}", fakeNoticePostedDate);
log.info("fake subject = {}", fakeNoticeSubject);
log.info("fake category = {}", fakeNoticeCategory);
log.debug("fake articleId = {}", fakeNoticeArticleId);
log.debug("fake postedDate = {}", fakeNoticePostedDate);
log.debug("fake subject = {}", fakeNoticeSubject);
log.debug("fake category = {}", fakeNoticeCategory);

try {
firebaseService.sendMessage(NoticeMessageDto.builder()
Expand Down Expand Up @@ -227,8 +227,8 @@ public FakeUpdateResponseDto enrollFakeUpdate(@RequestBody Map<String, String> r
String auth = reqBody.get("auth");
String type = reqBody.get("type");

log.info("fcm 토큰 = {}", token);
log.info("인증 토큰 = {}\n", auth);
log.debug("fcm 토큰 = {}", token);
log.debug("인증 토큰 = {}\n", auth);

boolean isAuthenticated = adminService.checkToken(auth);
if (!isAuthenticated) {
Expand All @@ -247,10 +247,10 @@ public FakeUpdateResponseDto enrollFakeUpdate(@RequestBody Map<String, String> r
String subject = reqBody.get("subject");
String category = reqBody.get("category");

log.info("제목 = {}", subject);
log.info("아이디 = {}", articleId);
log.info("게시일 = {}", postedDate);
log.info("카테고리 = {}", category);
log.debug("제목 = {}", subject);
log.debug("아이디 = {}", articleId);
log.debug("게시일 = {}", postedDate);
log.debug("카테고리 = {}", category);

boolean isCategorySupported = adminService.checkCategory(category);
if (!isCategorySupported) {
Expand Down Expand Up @@ -283,8 +283,8 @@ public FakeUpdateResponseDto enrollFakeUpdate(@RequestBody Map<String, String> r
String title = reqBody.get("title");
String body = reqBody.get("body");

log.info("제목 = {}", title);
log.info("내용 = {}", body);
log.debug("제목 = {}", title);
log.debug("내용 = {}", body);

boolean isTitleValid = adminService.checkTitle(title);
if (!isTitleValid) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,42 +19,42 @@ public class CommonExceptionHandler {

@ExceptionHandler
public ResponseEntity<ErrorResponse> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException exception) {
log.error("[MethodArgumentNotValidException] {}", exception.getMessage());
log.warn("[MethodArgumentNotValidException] {}", exception.getMessage());
return ResponseEntity.status(ErrorCode.API_MISSING_PARAM.getHttpStatus())
.body(new ErrorResponse(ErrorCode.API_MISSING_PARAM));
}

@ExceptionHandler
public ResponseEntity<ErrorResponse> NotFoundExceptionHandler(NotFoundException exception) {
log.error("[NotFoundException] {}", exception.getMessage());
log.warn("[NotFoundException] {}", exception.getMessage());
return ResponseEntity.status(exception.getErrorCode().getHttpStatus())
.body(new ErrorResponse(exception.getErrorCode()));
}

@ExceptionHandler(AdminException.class)
public ResponseEntity<ErrorResponse> AdminExceptionHandler(AdminException exception) {
log.error("[APIException] {}", exception.getErrorCode().getMessage(), exception);
log.warn("[APIException] {}", exception.getErrorCode().getMessage(), exception);
return ResponseEntity.status(exception.getErrorCode().getHttpStatus())
.body(new ErrorResponse(exception.getErrorCode()));
}

@ExceptionHandler
public ResponseEntity<ErrorResponse> MissingServletRequestParameterExceptionHandler(MissingServletRequestParameterException exception) {
log.error("[MissingServletRequestParameterException] {}", exception.getMessage());
log.warn("[MissingServletRequestParameterException] {}", exception.getMessage());
return ResponseEntity.status(ErrorCode.API_MISSING_PARAM.getHttpStatus())
.body(new ErrorResponse(ErrorCode.API_MISSING_PARAM));
}

@ExceptionHandler
public ResponseEntity<ErrorResponse> ConstraintViolationExceptionHandler(ConstraintViolationException exception) {
log.error("[ConstraintViolationException] {}", exception.getMessage());
log.warn("[ConstraintViolationException] {}", exception.getMessage());
return ResponseEntity.status(ErrorCode.API_INVALID_PARAM.getHttpStatus())
.body(new ErrorResponse(ErrorCode.API_INVALID_PARAM));
}

@ExceptionHandler
public ResponseEntity<ErrorResponse> HttpMediaTypeNotAcceptableExceptionHandler(HttpMediaTypeNotAcceptableException exception) {
log.error("[HttpMediaTypeNotAcceptableException] {}", exception.getMessage());
log.warn("[HttpMediaTypeNotAcceptableException] {}", exception.getMessage());
return ResponseEntity.status(ErrorCode.API_NOT_ACCEPTABLE.getHttpStatus())
.body(new ErrorResponse(ErrorCode.API_NOT_ACCEPTABLE));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@

import com.kustacks.kuring.common.annotation.CheckSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Expand All @@ -32,16 +30,16 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons

HttpSession session = request.getSession(false);
if(session != null) {
log.info("sessionId = {}", session.getId());
log.info("lastAccessedTime = {}", session.getLastAccessedTime());
log.debug("sessionId = {}", session.getId());
log.debug("lastAccessedTime = {}", session.getLastAccessedTime());
}

boolean isSessionFromCookie = session != null;
boolean isSessionRequired = checkSession.isSessionRequired();

// 세션이 있어야 하는 경우 - 없으면 로그인 페이지로 이동
if(isSessionRequired) {
log.info("isSessionFromCookie = {}", isSessionFromCookie);
log.debug("isSessionFromCookie = {}", isSessionFromCookie);
if(isSessionFromCookie) {
return true;
} else {
Expand All @@ -60,14 +58,4 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons
}
}
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable ModelAndView modelAndView) throws Exception {
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable Exception ex) throws Exception {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,7 @@ public void subscribe(String token, String topic) throws FirebaseSubscribeExcept
TopicManagementResponse response = firebaseMessaging
.subscribeToTopic(List.of(token), ifDevThenAddSuffix(topic).toString());

if (response.getFailureCount() > 0) {
throw new FirebaseSubscribeException();
}
responseLoggingAndException(response, "subscribe");
} catch (FirebaseMessagingException | FirebaseSubscribeException exception) {
throw new FirebaseSubscribeException();
}
Expand All @@ -65,9 +63,7 @@ public void unsubscribe(String token, String topic) throws FirebaseUnSubscribeEx
TopicManagementResponse response = firebaseMessaging
.unsubscribeFromTopic(List.of(token), ifDevThenAddSuffix(topic).toString());

if (response.getFailureCount() > 0) {
throw new FirebaseUnSubscribeException();
}
responseLoggingAndException(response, "unsubscribe");
} catch (FirebaseMessagingException | FirebaseUnSubscribeException exception) {
throw new FirebaseUnSubscribeException();
}
Expand Down Expand Up @@ -118,12 +114,12 @@ public void sendNotificationByFcm(List<? extends Notice> noticeList) {
try {
this.sendNoticeMessageList(notificationDtoList);
log.info("FCM에 {}개의 공지 메세지를 전송했습니다.", notificationDtoList.size());
log.info("전송된 공지 목록은 다음과 같습니다.");
log.debug("전송된 공지 목록은 다음과 같습니다.");
for (Notice notice : noticeList) {
log.info("아이디 = {}, 날짜 = {}, 카테고리 = {}, 제목 = {}", notice.getArticleId(), notice.getPostedDate(), notice.getCategoryName(), notice.getSubject());
log.debug("아이디 = {}, 날짜 = {}, 카테고리 = {}, 제목 = {}", notice.getArticleId(), notice.getPostedDate(), notice.getCategoryName(), notice.getSubject());
}
} catch (FirebaseMessageSendException e) {
log.error("새로운 공지의 FCM 전송에 실패했습니다.");
log.warn("새로운 공지의 FCM 전송에 실패했습니다.");
throw new InternalLogicException(ErrorCode.FB_FAIL_SEND, e);
} catch (Exception e) {
log.error("새로운 공지를 FCM에 보내는 중 알 수 없는 오류가 발생했습니다.");
Expand All @@ -141,6 +137,13 @@ private void sendNoticeMessageList(List<NoticeMessageDto> messageDtoList) throws
messageDtoList.forEach(this::sendMessage);
}

private static void responseLoggingAndException(TopicManagementResponse response, String methodName) throws FirebaseSubscribeException {
if (response.getFailureCount() > 0) {
log.warn("[{}] 구독 실패", methodName);
throw new FirebaseSubscribeException();
}
}

private String buildTitle(String korName) {
return new StringBuilder("[")
.append(korName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class FirebaseExceptionHandler {

@ExceptionHandler
public ResponseEntity<ErrorResponse> firebaseCommonExceptionHandler(FirebaseBusinessException exception) {
log.error("[FirebaseBusinessException] {}", exception.getMessage());
log.warn("[FirebaseBusinessException] {}", exception.getMessage());

return ResponseEntity.status(exception.getErrorCode().getHttpStatus())
.body(new ErrorResponse(exception.getErrorCode()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,25 @@ public class DepartmentNoticeScraperTemplate {
public List<ComplexNoticeFormatDto> scrap(DeptInfo deptInfo, Function<DeptInfo, List<ScrapingResultDto>> decisionMaker) throws InternalLogicException {
List<ScrapingResultDto> requestResults = requestWithDeptInfo(deptInfo, decisionMaker);

log.info("[{}] HTML 파싱 시작", deptInfo.getDeptName());
log.debug("[{}] HTML 파싱 시작", deptInfo.getDeptName());
List<ComplexNoticeFormatDto> noticeDtoList = htmlParsingFromScrapingResult(deptInfo, requestResults);
log.info("[{}] HTML 파싱 완료", deptInfo.getDeptName());
log.debug("[{}] HTML 파싱 완료", deptInfo.getDeptName());

for (ComplexNoticeFormatDto complexNoticeFormatDto : noticeDtoList) {
if (complexNoticeFormatDto.getNormalNoticeSize() == 0) {
throw new InternalLogicException(ErrorCode.NOTICE_SCRAPER_CANNOT_SCRAP);
}
}


return noticeDtoList;
}

private List<ScrapingResultDto> requestWithDeptInfo(DeptInfo deptInfo, Function<DeptInfo, List<ScrapingResultDto>> decisionMaker) {
long startTime = System.currentTimeMillis();

log.info("[{}] HTML 요청", deptInfo.getDeptName());
log.debug("[{}] HTML 요청", deptInfo.getDeptName());
List<ScrapingResultDto> reqResults = decisionMaker.apply(deptInfo);
log.info("[{}] HTML 수신", deptInfo.getDeptName());
log.debug("[{}] HTML 수신", deptInfo.getDeptName());

long endTime = System.currentTimeMillis();
log.info("[{}] 파싱에 소요된 초 = {}", deptInfo.getDeptName(), (endTime - startTime) / 1000.0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,21 +37,21 @@ public List<StaffDto> scrap(DeptInfo deptInfo) throws InternalLogicException {

for (StaffApiClient staffApiClient : staffApiClients) {
if (staffApiClient.support(deptInfo)) {
log.info("{} HTML 요청", deptInfo.getDeptName());
log.debug("{} HTML 요청", deptInfo.getDeptName());
documents = staffApiClient.getHTML(deptInfo);
log.info("{} HTML 수신", deptInfo.getDeptName());
log.debug("{} HTML 수신", deptInfo.getDeptName());
}
}

// 수신한 documents HTML 파싱
List<String[]> parseResult = new LinkedList<>();
for (StaffHtmlParser htmlParser : htmlParsers) {
if (htmlParser.support(deptInfo)) {
log.info("{} HTML 파싱 시작", deptInfo.getDeptName());
log.debug("{} HTML 파싱 시작", deptInfo.getDeptName());
for (Document document : documents) {
parseResult.addAll(htmlParser.parse(document));
}
log.info("{} HTML 파싱 완료", deptInfo.getDeptName());
log.debug("{} HTML 파싱 완료", deptInfo.getDeptName());
}
}

Expand All @@ -70,6 +70,7 @@ public List<StaffDto> scrap(DeptInfo deptInfo) throws InternalLogicException {
if (staffDtoList.isEmpty()) {
throw new InternalLogicException(ErrorCode.STAFF_SCRAPER_CANNOT_SCRAP);
}
log.info("[{}] 파싱된 교직원 수 = {}", deptInfo.getDeptName(), staffDtoList.size());

return staffDtoList;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ private Document proxyTemplate(String url, int timeOut, MethodCallback callback)
try {
return getDocument(url, timeOut, callback, proxyInfo);
} catch (SocketTimeoutException e) {
log.error("Jsoup time out 오류 발생. {}", e.getMessage());
log.warn("Jsoup time out 오류 발생. {}", e.getMessage());
} catch (IOException e) {
log.error("Jsoup 오류 발생. {}", e.getMessage());
log.warn("Jsoup 오류 발생. {}", e.getMessage());
proxyQueue.poll();
}
}
Expand All @@ -85,7 +85,7 @@ private Document getDocument(String url, int timeOut, MethodCallback callback, P

Document document = callback.sendRequest(connection, proxyInfo.getIp(), proxyInfo.getPort());

log.info("{} 으로 성공!", proxyInfo.ip);
log.info("{} 으로 성공 Scrap 성공", proxyInfo.ip);
return document;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public String getSessionId() {
}

if (!this.sessionNeedToBeRenew) { // apiSkeletonNeedToBeRenew가 true 이면 sessionNeedToBeRenew는 항상 true이므로 sessionNeedToBeRenew만 검사함.
log.info("세션아이디 갱신 안하고 바로 리턴");
log.debug("세션아이디 갱신 안하고 바로 리턴");
return parsingKuisAuthProperties.getSession();
}

Expand Down Expand Up @@ -136,7 +136,7 @@ private boolean isInvalidLoginResponse(ResponseEntity<String> loginResponse) {
throw new InternalLogicException(ErrorCode.KU_LOGIN_NO_RESPONSE_BODY);
}

log.info(body);
log.debug(body);
return !body.contains("success");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public List<ScrapingResultDto> requestAll(DeptInfo deptInfo) throws InternalLogi
ScrapingResultDto resultDto = getScrapingResultDto(i, deptInfo, totalNoticeSize, LATEST_SCRAP_ALL_TIMEOUT);
reqResults.add(resultDto);
} catch (IOException e) {
log.info("Department Scrap all IOException: {}", e.getMessage());
log.warn("Department Scrap all IOException: {}", e.getMessage());
} catch (NullPointerException | IndexOutOfBoundsException e) {
throw new InternalLogicException(ErrorCode.NOTICE_SCRAPER_CANNOT_PARSE, e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,12 @@ private List<CommonNoticeFormatDto> convertToCommonFormatDto(List<LibraryNoticeD

private void validateResponse(int requestIndex, LibraryNoticeResponseDto libraryNoticeResponseDto) {
if (libraryNoticeResponseDto == null) {
log.error("도서관 공지 {}번째 요청에 대한 응답의 body가 없습니다.", requestIndex + 1);
log.warn("도서관 공지 {}번째 요청에 대한 응답의 body가 없습니다.", requestIndex + 1);
throw new InternalLogicException(ErrorCode.LIB_CANNOT_PARSE_JSON);
}

if (!libraryNoticeResponseDto.isSuccess()) {
log.error("도서관 공지 {}번째 요청에 대한 응답이 fail입니다.", requestIndex + 1);
log.warn("도서관 공지 {}번째 요청에 대한 응답이 fail입니다.", requestIndex + 1);
throw new InternalLogicException(ErrorCode.LIB_BAD_RESPONSE);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public List<String[]> parse(Document document) throws InternalLogicException {

String jobPosition = String.valueOf(infos.get(1).childNodeSize() < 2 ? "" : infos.get(1).childNode(1));
if (jobPosition.contains("명예") || jobPosition.contains("대우") || jobPosition.contains("휴직") || !jobPosition.contains("교수")) {
log.info("스크래핑 스킵 -> {} 교수", oneStaffInfo[0]);
log.debug("스크래핑 스킵 -> {} 교수", oneStaffInfo[0]);
continue;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,10 @@ private List<Notice> filteringSoonSaveNotices(List<CommonNoticeFormatDto> scrapR
newNotices.add(newNotice);
}
} catch (IncorrectResultSizeDataAccessException e) {
log.error("오류가 발생한 공지 정보");
log.error("articleId = {}", notice.getArticleId());
log.error("postedDate = {}", notice.getPostedDate());
log.error("subject = {}", notice.getSubject());
log.warn("오류가 발생한 공지 정보");
log.warn("articleId = {}", notice.getArticleId());
log.warn("postedDate = {}", notice.getPostedDate());
log.warn("subject = {}", notice.getSubject());
}
}

Expand Down
Loading

0 comments on commit 5934043

Please sign in to comment.