Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CHORE] log level 변경 및 스케줄링 로깅 추가 #161

Merged
merged 1 commit into from
May 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
import java.time.LocalDateTime;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.PessimisticLockingFailureException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
Expand All @@ -16,7 +19,6 @@
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.PessimisticLockException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import sopt.org.motivoo.domain.mission.entity.CompletedStatus;
import sopt.org.motivoo.domain.mission.entity.Mission;
import sopt.org.motivoo.domain.mission.entity.MissionQuest;
Expand All @@ -28,11 +30,12 @@
import sopt.org.motivoo.domain.user.repository.UserRetriever;
import sopt.org.motivoo.external.s3.S3Service;

@Slf4j
@Component
@RequiredArgsConstructor
public class UserMissionScheduler {

private static final Logger logger = LoggerFactory.getLogger(ScheduledTask.class);

private final UserMissionRetriever userMissionRetriever;
private final UserRetriever userRetriever;
private final MissionRetriever missionRetriever;
Expand All @@ -46,27 +49,25 @@ public class UserMissionScheduler {


// 1. 미션 달성 상태 반영
@Scheduled(cron = "@daily", zone = "Asia/Seoul")
@Scheduled(cron = "0 0 0 * * *", zone = "Asia/Seoul")
public void setCompletedStatus() {
log.info("미션 달성상태 업데이트 스케줄러 진입");
logger.debug("미션 달성상태 업데이트 스케줄러 진입");

List<UserMission> missionsByCreatedAt = userMissionRetriever.getUserMissionsByCreatedDt(LocalDate.now().minusDays(1));
log.info("어제의 UserMission 개수: {}개", missionsByCreatedAt.size());
logger.trace("어제의 UserMission 개수: {}개", missionsByCreatedAt.size());
for (UserMission userMission : missionsByCreatedAt) {

// 수동 트랜잭션 처리
TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);

log.info(userMission.getMission().getContent());
log.info(userMission.getCompletedStatus().getValue());
if (userMission.getImgUrl() != null) {
try {
log.info("이미지가 올라왔으니 성공이어라..");
logger.trace("이미지가 올라왔으니 성공이어라..");
userMission.updateCompletedStatus(CompletedStatus.SUCCESS);

UserMission um = em.merge(userMission);
log.info("성공 상태로 업데이트 완료: {}", um.getCompletedStatus());
logger.trace("성공 상태로 업데이트 완료: {}", um.getCompletedStatus());
transactionManager.commit(transactionStatus);
} catch (PessimisticLockingFailureException | PessimisticLockException e) {
transactionManager.rollback(transactionStatus);
Expand All @@ -78,11 +79,11 @@ public void setCompletedStatus() {
if (!userMission.isEmptyUserMission() &&
(userMission.getCompletedStatus() != CompletedStatus.SUCCESS || userMission.getImgUrl() == null)) {
try {
log.info("성공이 아니니 실패여라..");
logger.trace("성공이 아니니 실패여라..");
userMission.updateCompletedStatus(CompletedStatus.FAIL);

UserMission um = em.merge(userMission);
log.info("실패 상태로 업데이트 완료: {}", um.getCompletedStatus());
logger.trace("실패 상태로 업데이트 완료: {}", um.getCompletedStatus());
transactionManager.commit(transactionStatus);
} catch (PessimisticLockingFailureException | PessimisticLockException e) {
transactionManager.rollback(transactionStatus);
Expand All @@ -96,24 +97,25 @@ public void setCompletedStatus() {


// 자정마다 오늘의 미션 초기값 bulk insert
@Scheduled(cron = "@daily", zone = "Asia/Seoul")
@Scheduled(cron = "0 0 0 * * *", zone = "Asia/Seoul")
public void insertEmptyUserMission() {
log.info("EmptyMission Bulk Insert");
logger.debug("EmptyMission Bulk Insert 🏁Start - {}", System.currentTimeMillis());
List<User> users = userRetriever.findAll().stream()
.filter(user -> !user.isDeleted())
.filter(user -> user.getParentchild().isMatched()).toList();
Mission emptyMission = missionRetriever.getEmptyMission();
MissionQuest missionQuest = missionQuestRetriever.getRandomMissionQuest();

userMissionRetriever.bulkSaveInitUserMission(users, LocalDate.now(), emptyMission, missionQuest);
log.info("User {} 명의 오늘의 미션 insert 성공", users.size());
logger.debug("User {} 명의 오늘의 미션 insert 성공", users.size());
logger.debug("EmptyMission Bulk Insert 🔚End - {}", System.currentTimeMillis());
}


// 매일 새벽 4시마다 30일 이전의 사진은 버킷에서 삭제한다
@Scheduled(cron = "0 0 4 * * *", zone = "Asia/Seoul")
public void deleteImgBefore30Days() {
log.info("30일 동안 보관한 이미지는 삭제");
logger.debug("30일 동안 보관한 이미지는 삭제");
LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);
userMissionRetriever.getUserMissionsByCreatedAtBefore(thirtyDaysAgo)
.forEach(um -> s3Service.deleteImage(um.getImgUrl()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.PessimisticLockingFailureException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
Expand All @@ -18,18 +21,18 @@
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.PessimisticLockException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import sopt.org.motivoo.batch.service.firebase.UserStepManager;
import sopt.org.motivoo.common.advice.BusinessException;
import sopt.org.motivoo.domain.mission.entity.UserMission;
import sopt.org.motivoo.domain.mission.service.UserMissionService;
import sopt.org.motivoo.domain.user.entity.User;

@Slf4j
@Component
@RequiredArgsConstructor
public class UserStepScheduler {

private static final Logger logger = LoggerFactory.getLogger(ScheduledTask.class);

private final UserMissionService userMissionService;
private final UserStepManager userStepManager;

Expand All @@ -39,23 +42,21 @@ public class UserStepScheduler {
private EntityManager em;


// @Scheduled(cron = "* */2 * * * *", zone = "Asia/Seoul")
@Scheduled(cron = "@daily", zone = "Asia/Seoul")
@Scheduled(cron = "0 0 0 * * *", zone = "Asia/Seoul")
public void flagUserStepInitialize() {
log.info("유저 걸음 수 초기화 스케줄러 실행");
logger.trace("유저 걸음 수 초기화 스케줄러 실행");
try {
userStepManager.insertUserStep();
log.info("스케줄러에서 유저 insert 성공");
logger.trace("스케줄러에서 유저 insert 성공");
// firebaseService.selectUser();
} catch (Exception e) {
log.error("파이어베이스 스케줄러 실행 중 발생한 에러: {}", e.getMessage());
logger.error("파이어베이스 스케줄러 실행 중 발생한 에러: {}", e.getMessage());
throw new BusinessException(FIREBASE_DB_INSERT_ERROR);
}
}

@Scheduled(fixedRate = 5000, zone = "Asia/Seoul")
public void readUserStep() {
log.info("유저 걸음 수 읽기 연산&상태 업데이트 스케줄러 실행");
try {
Map<User, Integer> userGoalSteps = userMissionService.getUsersGoalStep();
List<Long> ids = userGoalSteps.keySet().stream()
Expand All @@ -72,11 +73,11 @@ public void readUserStep() {
TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);

log.info("목표 걸음 수 {}를 넘은 현재 걸음 수 {}", userGoalSteps.get(user), result.get(String.valueOf(id)));
logger.trace("목표 걸음 수 {}를 넘은 현재 걸음 수 {}", userGoalSteps.get(user), result.get(String.valueOf(id)));
try {
user.getCurrentUserMission().updateCompletedStatus(STEP_COMPLETED);
UserMission u = em.merge(user.getCurrentUserMission());
log.info("User 미션 상태 반영 완료: {}", u.getCompletedStatus());
logger.trace("User 미션 상태 반영 완료: {}", u.getCompletedStatus());
transactionManager.commit(transactionStatus);
} catch (PessimisticLockingFailureException | PessimisticLockException e) {
transactionManager.rollback(transactionStatus);
Expand All @@ -86,9 +87,9 @@ public void readUserStep() {
}
}

log.info("스케줄러에서 유저 select 성공");
logger.trace("스케줄러에서 유저 select 성공");
} catch (Exception e) {
log.error("파이어베이스 스케줄러 실행 중 발생한 에러: {}", e.getMessage());
logger.error("파이어베이스 스케줄러 실행 중 발생한 에러: {}", e.getMessage());
throw new BusinessException(FIREBASE_DB_READ_ERROR);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ public void checkMissionChoice(UserMission todayMission) {
// 오늘의 미션에 대한 유효성 검사
public static boolean validateTodayDateMission(UserMission todayMission) {
if (!todayMission.isNowDate() || todayMission.isEmptyUserMission()) {
log.info("유효하지 않은 오늘의 미션! (아직 유저가 선택 X)");
log.debug("유효하지 않은 오늘의 미션! (아직 유저가 선택 X)");
return false;
}
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,15 @@ public class FirebaseService {
public void insertFBData(Map<String, Integer> values) {

ref.setValueAsync(values);
log.info("모든 활성 유저의 데이터 insert 성공!");
log.trace("모든 활성 유저의 데이터 insert 성공!");
}

public void updateFBData(Long id) {
Map<String, Object> values = new HashMap<>();
values.put(id.toString(), 0);
ref.updateChildrenAsync(values);

log.info("새로 가입한 유저의 데이터 insert 성공!");
log.trace("새로 가입한 유저의 데이터 insert 성공!");
}

public void selectAllUserStep() {
Expand Down Expand Up @@ -83,7 +83,7 @@ public void onCancelled(DatabaseError databaseError) {
}

latch.await(); // 모든 데이터를 받아올 때까지 기다립니다.
log.info("FB에서 가져온 Map 사이즈: {}", result.size());
log.trace("FB에서 가져온 Map 사이즈: {}", result.size());
return result;
}

Expand All @@ -94,20 +94,20 @@ public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String key = childSnapshot.getKey();
Object value = childSnapshot.getValue();
System.out.println(key + " : " + value.toString());
log.debug(key + " : " + value.toString());
}
}

@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("Failed to read value." + databaseError.toException());
log.error("Failed to read value." + databaseError.toException());
}
});
}

public void deleteUserStep(Map<String, Object> values) {
ref.updateChildrenAsync(values);

log.info("탈퇴한 유저의 데이터 delete 성공!");
log.trace("탈퇴한 유저의 데이터 delete 성공!");
}
}
Loading