Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -10,6 +10,7 @@
0522C1D72DB67B4F00B141FF /* RxSwift in Frameworks */ = {isa = PBXBuildFile; productRef = 0522C1D62DB67B4F00B141FF /* RxSwift */; };
05EC93D92DB6605100771CB3 /* RxCocoa in Frameworks */ = {isa = PBXBuildFile; productRef = 05EC93D82DB6605100771CB3 /* RxCocoa */; };
05EC93DE2DB6612100771CB3 /* RxGesture in Frameworks */ = {isa = PBXBuildFile; productRef = 05EC93DD2DB6612100771CB3 /* RxGesture */; };
4EBC91D32DB8039800495C3B /* OSLog.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4EBC91D22DB8039800495C3B /* OSLog.framework */; };
/* End PBXBuildFile section */

/* Begin PBXCopyFilesBuildPhase section */
Expand All @@ -27,6 +28,7 @@

/* Begin PBXFileReference section */
058CC9182DB5383C0084221A /* Infrastructure.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Infrastructure.framework; sourceTree = BUILT_PRODUCTS_DIR; };
4EBC91D22DB8039800495C3B /* OSLog.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OSLog.framework; path = System/Library/Frameworks/OSLog.framework; sourceTree = SDKROOT; };
/* End PBXFileReference section */

/* Begin PBXFileSystemSynchronizedRootGroup section */
Expand All @@ -42,6 +44,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
4EBC91D32DB8039800495C3B /* OSLog.framework in Frameworks */,
0522C1D72DB67B4F00B141FF /* RxSwift in Frameworks */,
05EC93DE2DB6612100771CB3 /* RxGesture in Frameworks */,
05EC93D92DB6605100771CB3 /* RxCocoa in Frameworks */,
Expand All @@ -54,6 +57,7 @@
05125B6A2DB56C32001342A2 /* Frameworks */ = {
isa = PBXGroup;
children = (
4EBC91D22DB8039800495C3B /* OSLog.framework */,
);
name = Frameworks;
sourceTree = "<group>";
Expand Down
71 changes: 32 additions & 39 deletions Poppool/CoreLayer/Infrastructure/Infrastructure/Logger/Logger.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import OSLog
public struct Logger {
private static let subsystem = Bundle.main.bundleIdentifier ?? "com.poppoolIOS.poppool"

public enum Level {
public enum Level: Hashable {
case info
case debug
case network
case error
case event
case custom(categoryName: String)
case custom(name: String)

var categoryName: String {
switch self {
Expand All @@ -24,8 +24,7 @@ public struct Logger {
return "Error"
case .event:
return "Event"
case .custom(let categoryName):
return categoryName
case .custom(let name): return name
}
}

Expand All @@ -45,70 +44,64 @@ public struct Logger {
return "🍎"
}
}
}

public enum LogLevel {
case debug
case info
case error
case fault

var osLogType: OSLogType {
switch self {
case .debug:
return .debug
case .info, .event:
case .info:
return .info
case .network:
return .default
case .error:
return .error
case .custom:
return .default
case .fault:
return .fault
}
}
}

static var isShowFileName: Bool = false // 파일 이름 포함여부
static var isShowLine: Bool = true // 라인 번호 포함 여부
static var isShowLog: Bool = true
/// : 아래 옵션 주석 해제시 파일명/라인 번호를 로그 메시지에 포함
// private static var isShowFileName: Bool = false // 파일 이름 포함 여부
// private static var isShowLine: Bool = true // 라인 번호 포함 여부
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

해당 프로퍼티를 사용하지 않는 것으로 보이는데 어디에서 사용되고 있는지 알 수 있을까요?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이전회의때 영훈님께서 로거의 위치를 알수가없다 하셔서 위와같은 기능이 있기에 추가해뒀다가 현재는 전문 제거되었습니다.

private static var isShowLog: Bool = true

private static var loggers: [String: os.Logger] = [:]
private static var loggers: [Level: os.Logger] = [:]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

결국 여러개의 로거를 쓰는것 같은데 혹시 로거가 여러개일때의 이점이 뭔지 알 수 있을까요?

지난번에도 달았던 코멘트였던거같은데 답변이 뭔가 제가 궁금해했던 부분을 정확히 긁어주진 못했던거 같아요 ㅠㅠ

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

질문의도를 제가 잘못파악했었군요...!!
카테고리로 예를들어 UI Network ...등등 어떤 계층에서 일어나는지 분류짓고
레벨로 위험도 라고 해야될까요? Debug 나 가령 error인지 지정해둘수있어 확인에 이점이있다 생각해서 추가해뒀습니다!

private static func getLogger(for category: Level) -> os.Logger {
let categoryName = category.categoryName

if let cachedLogger = loggers[categoryName] {
if let cachedLogger = loggers[category] {
return cachedLogger
}

let logger = os.Logger(subsystem: subsystem, category: categoryName)
loggers[categoryName] = logger
loggers[category] = logger
return logger
}

/// : 파일명과 라인 정보 파라미터 포함
// public static func log(
// _ message: Any,
// category: Level,
// level: LogLevel = .info,
// fileName: String = #file,
// line: Int = #line
// ) {
public static func log(
message: Any,
_ message: Any,
category: Level,
fileName: String = #file,
line: Int = #line
level: LogLevel = .info
) {
guard isShowLog else { return }

let logger = getLogger(for: category)
var fullMessage = "\(category.categoryIcon) \(message)"
let fullMessage = "\(category.categoryIcon) \(message)"

if isShowFileName {
guard let fileNameOnly = fileName.components(separatedBy: "/").last else { return }
fullMessage += " | 📁 \(fileNameOnly)"
}

if isShowLine {
fullMessage += " | 📍 \(line)"
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아 제가 리뷰했던거를 뭔가 그대로 받아들이신 부분인것 같아요 🥲

제가 말하려했던건 파일이름이랑 라인명이 필요 없다는게 아니라 해당 코드에서 fileName 대신에 #file처럼 바로 사용 가능한 변수가 있는데 그걸 쓰는건 어떠냐고 했던겁니다!!

저도 디버깅할때 파일명 라인명은 있는게 좋다 생각해서☺️

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아 ! 그렇군요 바로 사용가능한 변수명으로 지정해두는것이 저도 좋을것같습니다 ☺️


logger.log(level: category.osLogType, "\(fullMessage, privacy: .public)")

// 디버깅 시 Xcode 콘솔에서도 바로 확인할 수 있도록 print도 함께 사용 불필요시 제거
print("\(category.categoryIcon) [\(category.categoryName)]: \(message)")
if isShowFileName {
guard let fileNameOnly = fileName.components(separatedBy: "/").last else { return }
print(" \(category.categoryIcon) [FileName]: \(fileNameOnly)")
}
if isShowLine {
print(" \(category.categoryIcon) [Line]: \(line)")
}
logger.log(level: level.osLogType, "\(fullMessage, privacy: .public)")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public final class KeyChainService {
if let data = dataTypeRef as? Data {
if let value = String(data: data, encoding: .utf8) {
Logger.log(
message: "Successfully fetched \(type.rawValue) from KeyChain: \(value)",
"Successfully fetched \(type.rawValue) from KeyChain",
category: .info,
fileName: #file,
line: #line
Expand Down Expand Up @@ -84,7 +84,7 @@ public final class KeyChainService {
let status = SecItemAdd(keyChainQuery, nil)
if status == errSecSuccess {
Logger.log(
message: "Successfully saved \(type.rawValue) to KeyChain: \(value)",
"Successfully fetched \(type.rawValue) from KeyChain: \(value)",
category: .info,
fileName: #file,
line: #line
Expand All @@ -111,7 +111,7 @@ public final class KeyChainService {

if status == errSecSuccess {
Logger.log(
message: "Successfully deleted \(type.rawValue) from KeyChain",
"Successfully deleted \(type.rawValue) from KeyChain",
category: .info,
fileName: #file,
line: #line
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Infrastructure

struct PreSignedAPIEndPoint {
static func presigned_upload(request: PresignedURLRequestDTO) -> Endpoint<PreSignedURLResponseDTO> {
Logger.log(message: "Presigned URL 생성 - Request: \(request)", category: .debug)
Logger.log("Presigned URL 생성 - Request: \(request)", category: .debug)
return Endpoint(
baseURL: Secrets.popPoolBaseURL,
path: "/files/upload-preSignedUrl",
Expand All @@ -14,7 +14,7 @@ struct PreSignedAPIEndPoint {
}

static func presigned_download(request: PresignedURLRequestDTO) -> Endpoint<PreSignedURLResponseDTO> {
Logger.log(message: "Presigned Download URL 생성 - Request: \(request)", category: .debug)
Logger.log("Presigned Download URL 생성 - Request: \(request)", category: .debug)
return Endpoint(
baseURL: Secrets.popPoolBaseURL,
path: "/files/download-preSignedUrl",
Expand All @@ -24,7 +24,7 @@ struct PreSignedAPIEndPoint {
}

static func presigned_delete(request: PresignedURLRequestDTO) -> RequestEndpoint {
Logger.log(message: "Presigned Delete 생성 - Request: \(request)", category: .debug)
Logger.log("Presigned Delete 생성 - Request: \(request)", category: .debug)
return RequestEndpoint(
baseURL: Secrets.popPoolBaseURL,
path: "/files/delete",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ extension Requestable {
let url = try url()

Logger.log(
message: "\(url) URL 생성",
"\(url) URL 생성",
category: .network,
fileName: #file,
line: #line
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public class MultipartEndPoint: URLRequestConvertible {
public func asURLRequest() throws -> URLRequest {
let url = try baseURL.asURL().appendingPathComponent(path)
var request = URLRequest(url: url)
Logger.log(message: "\(request) URL 생성", category: .network)
Logger.log("\(request) URL 생성", category: .network)
request.method = method

if let headers = headers {
Expand All @@ -57,7 +57,7 @@ public class MultipartEndPoint: URLRequestConvertible {
multipartFormData.append(jsonString.data(using: .utf8)!, withName: "data")
}
} catch {
Logger.log(message: "JSON 변환 오류: \(error)", category: .network)
Logger.log("JSON 변환 오류: \(error)", category: .network)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ final class TokenInterceptor: RequestInterceptor {
_ urlRequest: URLRequest,
for session: Session,
completion: @escaping (Result<URLRequest, any Error>) -> Void) {
Logger.log(message: "TokenInterceptor Adapt Token", category: .network)
Logger.log("TokenInterceptor Adapt Token", category: .network)
@Dependency var keyChainService: KeyChainService
var urlRequest = urlRequest
let accessTokenResult = keyChainService.fetchToken(type: .accessToken)
Expand All @@ -32,7 +32,7 @@ final class TokenInterceptor: RequestInterceptor {
dueTo error: any Error,
completion: @escaping (RetryResult) -> Void
) {
Logger.log(message: "TokenInterceptor Retry Start", category: .network)
Logger.log("TokenInterceptor Retry Start", category: .network)
completion(.doNotRetry)
}
}
57 changes: 12 additions & 45 deletions Poppool/DataLayer/Data/Data/Network/Provider/ProviderImpl.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,22 +22,13 @@ public final class ProviderImpl: Provider {
/// 1) endpoint -> urlRequest 생성
let urlRequest = try endpoint.getUrlRequest()

Logger.log(
message: """
[Provider] 최종 요청 URL:
- URL: \(urlRequest.url?.absoluteString ?? "URL이 없습니다.")
- Method: \(urlRequest.httpMethod ?? "알 수 없음")
- Headers: \(urlRequest.allHTTPHeaderFields ?? [:])
요청 시각: \(Date())
""",
category: .debug
)


let request = AF.request(urlRequest, interceptor: interceptor)
.validate()
.responseData { [weak self] response in
Logger.log(
message: """
"""
[Provider] 응답 수신:
- URL: \(urlRequest.url?.absoluteString ?? "URL이 없습니다.")
- 응답 시각: \(Date())
Expand All @@ -63,14 +54,14 @@ public final class ProviderImpl: Provider {
observer.onCompleted()
} catch {
Logger.log(
message: "디코딩 실패: \(error.localizedDescription)",
"디코딩 실패: \(error.localizedDescription)",
category: .error
)
observer.onError(NetworkError.decodeError)
}

case .failure(let error):
Logger.log(message: "요청 실패 Error:\(error)", category: .error)
Logger.log("요청 실패 Error:\(error)", category: .error)
observer.onError(error)
}
}
Expand All @@ -80,7 +71,7 @@ public final class ProviderImpl: Provider {
}

} catch {
Logger.log(message: "[Provider] URLRequest 생성 실패: \(error.localizedDescription)", category: .error)
Logger.log("[Provider] URLRequest 생성 실패: \(error.localizedDescription)", category: .error)
observer.onError(NetworkError.urlRequest(error))
return Disposables.create()
}
Expand All @@ -101,19 +92,10 @@ public final class ProviderImpl: Provider {
do {
let urlRequest = try request.getUrlRequest()

Logger.log(
message: """
[Provider] 최종 요청 URL(Completable):
- URL: \(urlRequest.url?.absoluteString ?? "URL이 없습니다.")
- Method: \(urlRequest.httpMethod ?? "알 수 없음")
요청 시각: \(Date())
""",
category: .debug
)

self.executeRequest(urlRequest, interceptor: interceptor) { response in
Logger.log(
message: "응답 시각 :\(Date())",
"응답 시각 :\(Date())",
category: .network
)

Expand All @@ -132,12 +114,12 @@ public final class ProviderImpl: Provider {
case .success:
observer(.completed)
case .failure(let error):
Logger.log(message: "요청 실패 Error:\(error)", category: .error)
Logger.log("요청 실패 Error:\(error)", category: .error)
observer(.error(self.handleRequestError(response: response, error: error)))
}
}
} catch {
Logger.log(message: "[Provider] URLRequest 생성 실패 (Completable): \(error.localizedDescription)", category: .error)
Logger.log("[Provider] URLRequest 생성 실패 (Completable): \(error.localizedDescription)", category: .error)
observer(.error(NetworkError.urlRequest(error)))
}

Expand All @@ -158,23 +140,16 @@ public final class ProviderImpl: Provider {

do {
let urlRequest = try request.asURLRequest()
Logger.log(
message: """
[Provider] 이미지 업로드 요청:
- URL: \(urlRequest.url?.absoluteString ?? "URL이 없습니다.")
- Method: \(urlRequest.httpMethod ?? "알 수 없음")
""",
category: .network
)


AF.upload(multipartFormData: { multipartFormData in
request.asMultipartFormData(multipartFormData: multipartFormData)
Logger.log(message: "업로드 시각 :\(Date())", category: .network)
Logger.log("업로드 시각 :\(Date())", category: .network)
}, with: urlRequest, interceptor: interceptor)
.validate()
.response { response in
Logger.log(
message: "이미지 업로드 응답 시각 :\(Date())",
"이미지 업로드 응답 시각 :\(Date())",
category: .network
)
switch response.result {
Expand All @@ -200,15 +175,7 @@ private extension ProviderImpl {
interceptor: RequestInterceptor?,
completion: @escaping (AFDataResponse<Data?>) -> Void
) {
// 여기서도 최종 URL 찍을 수 있음
Logger.log(
message: """
[Provider] executeRequest:
- URL: \(urlRequest.url?.absoluteString ?? "URL이 없습니다.")
요청 시각: \(Date())
""",
category: .debug
)


AF.request(urlRequest, interceptor: interceptor)
.validate()
Expand Down
Loading