From 0f1c5443eafbbfc117ed865cf288fa910a5cf945 Mon Sep 17 00:00:00 2001 From: sohot8653 Date: Fri, 15 Aug 2025 00:53:17 +0900 Subject: [PATCH] =?UTF-8?q?[=EB=A1=9C=EA=B7=B8=20=EA=B8=B0=EB=8A=A5=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80]=20HttpLoggingFilter=EB=A5=BC=20=EA=B5=AC?= =?UTF-8?q?=ED=98=84=ED=95=98=EC=97=AC=20HTTP=20=EC=9A=94=EC=B2=AD=20?= =?UTF-8?q?=EB=B0=8F=20=EC=9D=91=EB=8B=B5=20=EB=A1=9C=EA=B9=85=20=EA=B8=B0?= =?UTF-8?q?=EB=8A=A5=EC=9D=84=20=EC=B6=94=EA=B0=80=ED=95=98=EA=B3=A0,=20Me?= =?UTF-8?q?mberController=EC=97=90=EC=84=9C=20=ED=9A=8C=EC=9B=90=20?= =?UTF-8?q?=EB=93=B1=EB=A1=9D=20API=EC=97=90=20LogExecution=20=EC=96=B4?= =?UTF-8?q?=EB=85=B8=ED=85=8C=EC=9D=B4=EC=85=98=EC=9D=84=20=EC=A0=81?= =?UTF-8?q?=EC=9A=A9=ED=95=98=EC=97=AC=20=EC=8B=A4=ED=96=89=20=EB=A1=9C?= =?UTF-8?q?=EA=B7=B8=EB=A5=BC=20=EA=B8=B0=EB=A1=9D=ED=95=98=EB=8F=84?= =?UTF-8?q?=EB=A1=9D=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 53 ++++++ .../member/controller/MemberController.java | 4 +- .../global/annotation/LogExecution.java | 15 ++ .../aop/MethodExecutionLoggingAspect.java | 55 ++++++ .../global/filter/HttpLoggingFilter.java | 166 ++++++++++++------ src/main/resources/application.properties | 88 +++++++--- src/main/resources/logback-spring.xml | 92 ++++++++++ 7 files changed, 387 insertions(+), 86 deletions(-) create mode 100644 src/main/java/com/bio/bio_backend/global/annotation/LogExecution.java create mode 100644 src/main/java/com/bio/bio_backend/global/aop/MethodExecutionLoggingAspect.java create mode 100644 src/main/resources/logback-spring.xml diff --git a/README.md b/README.md index a142501..cbc77af 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ src/main/java/com/bio/bio_backend/ │ ├── config/ # 설정 클래스 │ ├── security/ # 보안 설정 │ ├── exception/ # 예외 처리 +│ ├── aop/ # AOP 로깅 +│ ├── filter/ # HTTP 로깅 필터 │ └── utils/ # 유틸리티 └── BioBackendApplication.java ``` @@ -195,3 +197,54 @@ throw new ApiException(ApiResponseCode.USER_ID_DUPLICATE); - **오류 코드**: `ApiResponseCode` enum에 모든 오류 정의 - **예외 클래스**: `ApiException`으로 비즈니스 로직 예외 처리 - **자동 처리**: `GlobalExceptionHandler`가 일관된 응답 형태로 변환 + +### 6. 로깅 시스템 + +#### @LogExecution 어노테이션 사용법 + +**메서드 실행 로깅을 위한 필수 어노테이션입니다.** + +##### 기본 사용법 + +```java +@LogExecution("회원 등록") +@PostMapping("/register") +public ResponseEntity> createMember(@RequestBody CreateMemberRequestDto requestDto) { + // 메서드 실행 시 자동으로 로그 출력 +} +``` + +##### 로그 출력 예시 + +**메서드 시작 시:** +``` +[START] 회원 등록 | 호출경로: MemberController.createMember | 사용자: 고명빈(kmbin92) +``` + +**메서드 성공 시:** +``` +[SUCCESS] 회원 등록 | 호출경로: MemberController.createMember | 사용자: 고명빈(kmbin92) | 시간: 200ms +``` + +**메서드 실패 시:** +``` +[FAILED] 회원 등록 | 호출경로: MemberController.createMember | 사용자: 고명빈(kmbin92) | 시간: 23ms | 오류: 이미 존재하는 사용자 ID입니다 +``` + +##### 어노테이션 설정 + +```java +@LogExecution("사용자 정보 조회") +public UserDto getUserInfo() { } + +@LogExecution("주문 처리") +public OrderDto processOrder() { } +``` + +##### 로깅 시스템 구성 + +1. **MethodExecutionLoggingAspect**: 메서드 실행 로깅 (AOP) +2. **HttpLoggingFilter**: HTTP 요청/응답 로깅 (필터) +3. **logback-spring.xml**: 로그 파일 관리 및 설정 + +**중요**: `@LogExecution` 어노테이션이 없으면 메서드 실행 로그가 출력되지 않습니다 diff --git a/src/main/java/com/bio/bio_backend/domain/user/member/controller/MemberController.java b/src/main/java/com/bio/bio_backend/domain/user/member/controller/MemberController.java index 7c6efb1..284b9fe 100644 --- a/src/main/java/com/bio/bio_backend/domain/user/member/controller/MemberController.java +++ b/src/main/java/com/bio/bio_backend/domain/user/member/controller/MemberController.java @@ -21,6 +21,7 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import com.bio.bio_backend.global.constants.ApiResponseCode; +import com.bio.bio_backend.global.annotation.LogExecution; @Tag(name = "Member", description = "회원 관련 API") @RestController @@ -33,7 +34,8 @@ public class MemberController { private final MemberMapper memberMapper; private final BCryptPasswordEncoder bCryptPasswordEncoder; - @Operation(summary = "회원 가입", description = "새로운 회원을 등록합니다.") + @LogExecution("회원 등록") + @Operation(summary = "회원 등록", description = "새로운 회원을 등록합니다.") @ApiResponses({ @ApiResponse(responseCode = "201", description = "회원 가입 성공"), @ApiResponse(responseCode = "400", description = "잘못된 요청 데이터", content = @Content(schema = @Schema(implementation = ApiResponseDto.class))), diff --git a/src/main/java/com/bio/bio_backend/global/annotation/LogExecution.java b/src/main/java/com/bio/bio_backend/global/annotation/LogExecution.java new file mode 100644 index 0000000..7ca161d --- /dev/null +++ b/src/main/java/com/bio/bio_backend/global/annotation/LogExecution.java @@ -0,0 +1,15 @@ +package com.bio.bio_backend.global.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 메서드 실행 로깅 어노테이션 + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface LogExecution { + String value() default ""; +} diff --git a/src/main/java/com/bio/bio_backend/global/aop/MethodExecutionLoggingAspect.java b/src/main/java/com/bio/bio_backend/global/aop/MethodExecutionLoggingAspect.java new file mode 100644 index 0000000..3041aa1 --- /dev/null +++ b/src/main/java/com/bio/bio_backend/global/aop/MethodExecutionLoggingAspect.java @@ -0,0 +1,55 @@ +package com.bio.bio_backend.global.aop; + +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; + +@Aspect +@Component +@Slf4j +public class MethodExecutionLoggingAspect { + + @Around("@annotation(logExecution)") + public Object logExecution(ProceedingJoinPoint pjp, com.bio.bio_backend.global.annotation.LogExecution logExecution) throws Throwable { + String message = logExecution.value().isEmpty() ? + pjp.getSignature().getName() : logExecution.value(); + + String className = pjp.getTarget().getClass().getSimpleName(); + String methodName = pjp.getSignature().getName(); + + String userInfo = getCurrentUser(); + + long startTime = System.currentTimeMillis(); + log.info("[START] {} | 호출경로: {}.{} | 사용자: {}", + message, className, methodName, userInfo); + + try { + Object result = pjp.proceed(); + long duration = System.currentTimeMillis() - startTime; + log.info("[SUCCESS] {} | 호출경로: {}.{} | 사용자: {} | 시간: {}ms", + message, className, methodName, userInfo, duration); + return result; + } catch (Exception e) { + long duration = System.currentTimeMillis() - startTime; + log.error("[FAILED] {} | 호출경로: {}.{} | 사용자: {} | 시간: {}ms | 오류: {}", + message, className, methodName, userInfo, duration, e.getMessage()); + throw e; + } + } + + private String getCurrentUser() { + try { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null && auth.isAuthenticated() && !"anonymousUser".equals(auth.getName())) { + return auth.getName(); + } + return "인증되지 않은 사용자"; + } catch (Exception e) { + return "알 수 없는 사용자"; + } + } +} diff --git a/src/main/java/com/bio/bio_backend/global/filter/HttpLoggingFilter.java b/src/main/java/com/bio/bio_backend/global/filter/HttpLoggingFilter.java index 91c98dd..80ee717 100644 --- a/src/main/java/com/bio/bio_backend/global/filter/HttpLoggingFilter.java +++ b/src/main/java/com/bio/bio_backend/global/filter/HttpLoggingFilter.java @@ -1,57 +1,109 @@ -//package com.bio.bio_backend.filter; -// -//import java.io.IOException; -//import java.sql.Timestamp; -// -//import org.springframework.security.core.Authentication; -//import org.springframework.security.core.context.SecurityContextHolder; -//import org.springframework.web.filter.OncePerRequestFilter; -// -//import jakarta.servlet.FilterChain; -//import jakarta.servlet.ServletException; -//import jakarta.servlet.http.HttpServletRequest; -//import jakarta.servlet.http.HttpServletResponse; -//import com.bio.bio_backend.domain.common.dto.AccessLogDTO; -//import com.bio.bio_backend.domain.common.service.AccessLogService; -//import com.bio.bio_backend.domain.user.member.dto.MemberDTO; -//import com.bio.bio_backend.global.utils.HttpUtils; -// -//public class HttpLoggingFilter extends OncePerRequestFilter { -// -//// private AccessLogService accessLogService; -// private HttpUtils httpUtils; -// -// public HttpLoggingFilter(AccessLogService accessLogService, HttpUtils httpUtils) { -// this.accessLogService = accessLogService; -// this.httpUtils = httpUtils; -// } -// -// @Override -// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) -// throws ServletException, IOException { -// // Request 요청 시간 -// Long startedAt = System.currentTimeMillis(); -// filterChain.doFilter(request, response); -// Long finishedAt = System.currentTimeMillis(); -// -// Authentication auth = SecurityContextHolder.getContext().getAuthentication(); -// MemberDTO member = null; -// if(auth != null && auth.getPrincipal() instanceof MemberDTO) { -// member = (MemberDTO) auth.getPrincipal(); -// } -// -// AccessLogDTO log = new AccessLogDTO(); -// log.setMbrSeq(member == null ? -1 : member.getSeq()); -// log.setType(httpUtils.getResponseType(response.getContentType())); -// log.setMethod(request.getMethod()); -// log.setIp(httpUtils.getClientIp()); -// log.setUri(request.getRequestURI()); -// log.setReqAt(new Timestamp(startedAt)); -// log.setResAt(new Timestamp(finishedAt)); -// log.setElapsedTime(finishedAt - startedAt); -// log.setResStatus(String.valueOf(response.getStatus())); -// -// accessLogService.createAccessLog(log); -// } -// -//} +package com.bio.bio_backend.global.filter; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; +import org.springframework.web.util.ContentCachingRequestWrapper; +import org.springframework.web.util.ContentCachingResponseWrapper; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@Component +public class HttpLoggingFilter extends OncePerRequestFilter { + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + + long startTime = System.currentTimeMillis(); + + // 요청 정보 로깅 (IP 정보 제거) + log.info("HTTP REQUEST: {} {} | Headers: {} | Body: {}", + request.getMethod(), request.getRequestURI(), + getRequestHeaders(request), getRequestBody(request)); + + ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request); + ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(response); + + try { + filterChain.doFilter(wrappedRequest, wrappedResponse); + } finally { + long duration = System.currentTimeMillis() - startTime; + + // 응답 정보 로깅 + log.info("HTTP RESPONSE: {} {} | Status: {} | Time: {}ms | Headers: {} | Body: {}", + request.getMethod(), request.getRequestURI(), + wrappedResponse.getStatus(), duration, getResponseHeaders(wrappedResponse), getResponseBody(wrappedResponse)); + + wrappedResponse.copyBodyToResponse(); + } + } + + // 민감 정보 마스킹 메서드 + private String maskSensitiveData(String body) { + if (body == null || body.isEmpty()) return "N/A"; + + // 비밀번호, 토큰 등 민감 정보 마스킹 + return body.replaceAll("\"password\"\\s*:\\s*\"[^\"]*\"", "\"password\":\"***\"") + .replaceAll("\"token\"\\s*:\\s*\"[^\"]*\"", "\"token\":\"***\"") + .replaceAll("\"refreshToken\"\\s*:\\s*\"[^\"]*\"", "\"refreshToken\":\"***\""); + } + + private String getRequestHeaders(HttpServletRequest request) { + // 주요 헤더만 (Content-Type, Authorization, User-Agent) + Map headers = new HashMap<>(); + headers.put("Content-Type", request.getContentType()); + headers.put("User-Agent", request.getHeader("User-Agent")); + + // Authorization 헤더는 마스킹 + String auth = request.getHeader("Authorization"); + if (auth != null) { + headers.put("Authorization", auth.startsWith("Bearer ") ? "Bearer ***" : "***"); + } + + return headers.toString(); + } + + private String getRequestBody(HttpServletRequest request) { + try { + ContentCachingRequestWrapper wrapper = (ContentCachingRequestWrapper) request; + String body = new String(wrapper.getContentAsByteArray()); + return maskSensitiveData(body); + } catch (Exception e) { + return "N/A"; + } + } + + private String getResponseHeaders(HttpServletResponse response) { + // 응답 헤더 정보 + return "Content-Type: " + response.getContentType(); + } + + private String getResponseBody(HttpServletResponse response) { + try { + ContentCachingResponseWrapper wrapper = (ContentCachingResponseWrapper) response; + String body = new String(wrapper.getContentAsByteArray()); + return maskSensitiveData(body); + } catch (Exception e) { + return "N/A"; + } + } + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + String path = request.getRequestURI(); + return path.startsWith("/static/") || + path.startsWith("/css/") || + path.startsWith("/js/") || + path.startsWith("/images/") || + path.equals("/actuator/health") || + path.equals("/favicon.ico"); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 78a0296..667b6cf 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,60 +1,92 @@ +# ======================================== +# 기본 애플리케이션 설정 +# ======================================== server.port=8080 server.servlet.context-path=/service spring.application.name=bio_backend +spring.output.ansi.enabled=always + +# ======================================== +# 개발 도구 설정 +# ======================================== spring.devtools.livereload.enabled=true -#spring.devtools.restart.poll-interval=2000 -# 추가로 감시할 경로 (자바 소스 폴더) spring.devtools.restart.additional-paths=src/main/java - -# 데이터베이스 연결 정보 -# URL 형식: jdbc:postgresql://[호스트명]:[포트번호]/[데이터베이스명] +# ======================================== +# 데이터베이스 설정 +# ======================================== spring.datasource.url=jdbc:postgresql://stam.kr:15432/imas spring.datasource.username=imas_user spring.datasource.password=stam1201 spring.datasource.driver-class-name=org.postgresql.Driver +# ======================================== # JPA/Hibernate 설정 -# ddl-auto: 엔티티(Entity)에 맞춰 데이터베이스 스키마를 자동 생성/업데이트합니다. -# - create: 애플리케이션 시작 시 기존 스키마를 삭제하고 새로 생성 (개발용) -# - create-drop: 시작 시 생성, 종료 시 삭제 (테스트용) -# - update: 엔티티 변경 시 스키마 업데이트 (개발용) -# - validate: 엔티티와 스키마 일치 여부만 검증 (운영용) -# - none: 아무 작업도 하지 않음 +# ======================================== spring.jpa.hibernate.ddl-auto=none -spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create -spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=ddl/schema.sql -spring.jpa.properties.hibernate.hbm2ddl.schema-generation.script.append=false - -# Hibernate log +spring.jpa.open-in-view=false spring.jpa.show-sql=false spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.highlight_sql=true spring.jpa.properties.hibernate.use_sql_comments=false + +# 스키마 생성 설정 +spring.jpa.properties.javax.persistence.schema-generation.scripts.action=create +spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=ddl/schema.sql +spring.jpa.properties.hibernate.hbm2ddl.schema-generation.script.append=false + +# ======================================== +# 로그 레벨 설정 +# ======================================== +# 전체 애플리케이션 기본 로그 레벨 +logging.level.root=INFO + +# 프로젝트 패키지 로그 레벨 +logging.level.com.bio.bio_backend=DEBUG + +# 세부 패키지별 로그 레벨 +logging.level.com.bio.bio_backend..*.controller=INFO +logging.level.com.bio.bio_backend..*.service=DEBUG +logging.level.com.bio.bio_backend..*.repository=DEBUG +logging.level.com.bio.bio_backend.global.aop=DEBUG +logging.level.com.bio.bio_backend.global.filter=INFO + +# JPA/Hibernate 로깅 logging.level.org.hibernate.SQL=DEBUG logging.level.org.hibernate.orm.jdbc.bind=TRACE +logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE logging.level.org.springframework.data.jpa=DEBUG +logging.level.org.springframework.orm.jpa=INFO +logging.level.org.springframework.transaction=DEBUG -# Open Session in View 설정 (권장: false) -spring.jpa.open-in-view=false +# Spring Framework 로깅 +logging.level.org.springframework.web=WARN +logging.level.org.springframework.web.servlet.DispatcherServlet=WARN +logging.level.org.springframework.security=INFO -# P6Spy + +# ======================================== +# 로그 패턴 설정 +# ======================================== +logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n +logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + +# ======================================== +# P6Spy 설정 (SQL 로깅) +# ======================================== decorator.datasource.p6spy.enable-logging=true decorator.datasource.p6spy.log-format=%(sqlSingleLine) -# CONSOLE -spring.output.ansi.enabled=always - -# HikariCP 연결 풀 크기 설정 (선택사항) -# spring.datasource.hikari.maximum-pool-size=10 - -##JWT 설정 -## access : 30분 / refresh : 7일 +# ======================================== +# JWT 설정 +# ======================================== token.expiration_time_access=180000 token.expiration_time_refresh=604800000 -token.secret_key= c3RhbV9qd3Rfc2VjcmV0X3Rva2Vuc3RhbV9qd3Rfc2VjcmV0X3Rva2Vu +token.secret_key=c3RhbV9qd3Rfc2VjcmV0X3Rva2Vuc3RhbV9qd3Rfc2VjcmV0X3RhbV9qd3Rfc2VjcmV0X3Rva2Vu +# ======================================== # Swagger 설정 +# ======================================== springdoc.api-docs.path=/api-docs springdoc.swagger-ui.path=/swagger-ui.html springdoc.swagger-ui.operationsSorter=method diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..1eab898 --- /dev/null +++ b/src/main/resources/logback-spring.xml @@ -0,0 +1,92 @@ + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + logs/bio-backend.log + + + logs/bio-backend-%d{yyyy-MM-dd}.%i.log + + 30 + + 10MB + + 1GB + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + logs/bio-backend-error.log + + ERROR + ACCEPT + DENY + + + logs/bio-backend-error-%d{yyyy-MM-dd}.%i.log + 30 + 10MB + 500MB + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file