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

[APP-2881] Add a log level of verbose/standard/light to the SDK Config #101

Merged
merged 6 commits into from
Jun 26, 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
2 changes: 1 addition & 1 deletion Example/CreativeUITest/CreativeUITest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ final class CreativeUITest: XCTestCase, BaseXCTestCase {

HomePage
.tapOnPushMeToCreative()
.addDelay(seconds: 4)
.addDelay(seconds: 5)

CreativePage
.tapOnCloseCreative()
Expand Down
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import PackageDescription

let package = Package(
name: "ATTNSDKFramework",
platforms: [.iOS(.v12)],
platforms: [.iOS(.v14)],
products: [
.library(name: "ATTNSDKFramework", targets: ["ATTNSDKFramework", "ATTNSDKFrameworkObjc"])
],
Expand Down
54 changes: 26 additions & 28 deletions Sources/API/ATTNAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ final class ATTNAPI: ATTNAPIProtocol {
func send(userIdentity: ATTNUserIdentity, callback: ATTNAPICallback?) {
getGeoAdjustedDomain(domain: domain) { [weak self] geoAdjustedDomain, error in
if let error = error {
NSLog("Error sending user identity: '%@'", error.localizedDescription)
Loggers.network.error("Error sending user identity: \(error.localizedDescription)")
return
}

Expand All @@ -59,11 +59,12 @@ final class ATTNAPI: ATTNAPIProtocol {
func send(event: ATTNEvent, userIdentity: ATTNUserIdentity, callback: ATTNAPICallback?) {
getGeoAdjustedDomain(domain: domain) { [weak self] geoAdjustedDomain, error in
if let error = error {
NSLog("Error sending user identity: '%@'", error.localizedDescription)
Loggers.network.error("Error sending event: \(error.localizedDescription)")
return
}

guard let geoAdjustedDomain = geoAdjustedDomain else { return }
Loggers.network.debug("Successfully returned geoAdjustedDomain: \(geoAdjustedDomain, privacy: .public)")
self?.sendEventInternal(event: event, userIdentity: userIdentity, domain: geoAdjustedDomain, callback: callback)
}
}
Expand All @@ -86,26 +87,24 @@ fileprivate extension ATTNAPI {

func sendEventInternalForRequest(request: ATTNEventRequest, userIdentity: ATTNUserIdentity, domain: String, callback: ATTNAPICallback?) {
guard let url = eventUrlProvider.buildUrl(for: request, userIdentity: userIdentity, domain: domain) else {
NSLog("Invalid URL constructed for event request.")
Loggers.event.error("Invalid URL constructed for event request.")
return
}

Loggers.event.debug("Building Event URL: \(url)")

var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"

let task = urlSession.dataTask(with: urlRequest) { data, response, error in
let message: String

if let error = error {
message = "Error sending for event '\(request.eventNameAbbreviation)'. Error: '\(error.localizedDescription)'"
Loggers.event.error("Error sending for event '\(request.eventNameAbbreviation)'. Error: '\(error.localizedDescription)'")
} else if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode > 400 {
message = "Error sending the event. Incorrect status code: '\(httpResponse.statusCode)'"
Loggers.event.error("Error sending the event. Incorrect status code: '\(httpResponse.statusCode)'")
} else {
message = "Successfully sent event of type '\(request.eventNameAbbreviation)'"
Loggers.event.debug("Successfully sent event of type '\(request.eventNameAbbreviation)'")
}

NSLog("%@", message)

callback?(data, url, response, error)
}

Expand All @@ -114,26 +113,24 @@ fileprivate extension ATTNAPI {

func sendUserIdentityInternal(userIdentity: ATTNUserIdentity, domain: String, callback: ATTNAPICallback?) {
guard let url = eventUrlProvider.buildUrl(for: userIdentity, domain: domain) else {
NSLog("Invalid URL constructed for user identity.")
Loggers.event.error("Invalid URL constructed for user identity.")
return
}

Loggers.event.debug("Building Identity Event URL: \(url)")

var request = URLRequest(url: url)
request.httpMethod = "POST"

let task = urlSession.dataTask(with: request) { data, response, error in
let message: String

if let error = error {
message = "Error sending user identity. Error: '\(error.localizedDescription)'"
Loggers.event.error("Error sending user identity. Error: '\(error.localizedDescription)'")
} else if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode > 400 {
message = "Error sending the event. Incorrect status code: '\(httpResponse.statusCode)'"
Loggers.event.error("Error sending the event. Incorrect status code: '\(httpResponse.statusCode)'")
} else {
message = "Successfully sent user identity event"
Loggers.event.debug("Successfully sent user identity event")
}

NSLog("%@", message)

callback?(data, url, response, error)
}

Expand All @@ -146,26 +143,26 @@ fileprivate extension ATTNAPI {
let matchesCount = regex.numberOfMatches(in: tag, options: [], range: NSRange(location: 0, length: tag.utf16.count))

guard matchesCount >= 1 else {
NSLog("No Attentive domain found in the tag")
Loggers.creative.debug("No Attentive domain found in the tag")
return nil
}

guard let match = regex.firstMatch(in: tag, options: [], range: NSRange(location: 0, length: tag.utf16.count)) else {
NSLog("No Attentive domain regex match object returned.")
Loggers.creative.debug("No Attentive domain regex match object returned.")
return nil
}

let domainRange = match.range(at: 1)
guard domainRange.location != NSNotFound, let range = Range(domainRange, in: tag) else {
NSLog("No match found for Attentive domain in the tag.")
Loggers.creative.debug("No match found for Attentive domain in the tag.")
return nil
}

let regionalizedDomain = String(tag[range])
NSLog("Identified regionalized attentive domain: %@", regionalizedDomain)
Loggers.creative.debug("Identified regionalized attentive domain: \(regionalizedDomain)")
return regionalizedDomain
} catch {
NSLog("Error building the domain regex. Error: '%@'", error.localizedDescription)
Loggers.creative.debug("Error building the domain regex. Error: '\(error.localizedDescription)'")
return nil
}
}
Expand All @@ -178,31 +175,31 @@ extension ATTNAPI {
return
}

NSLog("Getting the geoAdjustedDomain for domain '%@'...", domain)
Loggers.network.debug("Getting the geoAdjustedDomain for domain '\(domain)'...")

let urlString = String(format: RequestConstants.dtagUrlFormat, domain)
guard let url = URL(string: urlString) else {
NSLog("Invalid URL format for domain '%@'", domain)
Loggers.network.debug("Invalid URL format for domain '\(domain)'")
completionHandler(nil, NSError(domain: "com.attentive.API", code: NSURLErrorBadURL, userInfo: nil))
return
}

let request = URLRequest(url: url)
let task = urlSession.dataTask(with: request) { [weak self] data, response, error in
if let error = error {
NSLog("Error getting the geo-adjusted domain. Error: '%@'", error.localizedDescription)
Loggers.network.error("Error getting the geo-adjusted domain for \(domain). Error: '\(error.localizedDescription)'")
completionHandler(nil, error)
return
}

guard let httpResponse = response as? HTTPURLResponse else {
NSLog("Invalid response received.")
Loggers.network.error("Invalid response received.")
completionHandler(nil, NSError(domain: "com.attentive.API", code: NSURLErrorUnknown, userInfo: nil))
return
}

guard httpResponse.statusCode == 200, let data = data else {
NSLog("Error getting the geo-adjusted domain. Incorrect status code: '%ld'", httpResponse.statusCode)
Loggers.network.error("Error getting the geo-adjusted domain for \(domain). Incorrect status code: '\(httpResponse.statusCode)'")
completionHandler(nil, NSError(domain: "com.attentive.API", code: NSURLErrorBadServerResponse, userInfo: nil))
return
}
Expand All @@ -211,6 +208,7 @@ extension ATTNAPI {
guard let geoAdjustedDomain = ATTNAPI.extractDomainFromTag(dataString ?? "") else { return }

if geoAdjustedDomain.isEmpty {
Loggers.network.error("Invalid empty geo-adjusted domain")
let error = NSError(domain: "com.attentive.API", code: NSURLErrorBadServerResponse, userInfo: nil)
completionHandler(nil, error)
return
Expand Down
4 changes: 2 additions & 2 deletions Sources/ATTNParameterValidation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ struct ATTNParameterValidation {

static func verifyNotNil(_ inputValue: NSObject?, inputName: String) {
guard isNil(inputValue) else { return }
NSLog("Input was nil; %@ should be non-nil", inputName)
Loggers.event.debug("Input was nil; \(inputName) should be non-nil")
}

static func verifyStringOrNil(_ inputValue: NSObject?, inputName: String) {
guard isNil(inputValue) else { return }
guard !isString(inputValue) || isEmpty(inputName) else { return }
NSLog("Identifier %@ should be a non-empty NSString", inputName)
Loggers.event.debug("Identifier \(inputName) should be a non-empty NSString")
}

static func verify1DStringDictionaryOrNil(_ inputValue: NSDictionary?, inputName: String) {
Expand Down
6 changes: 5 additions & 1 deletion Sources/ATTNUserAgentBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class ATTNUserAgentBuilder: ATTNUserAgentBuilderProtocol {

func buildUserAgent() -> String {
// We replace the spaces with dashes for the app name because spaces in a User-Agent represent a new "product", so app names that have spaces are harder to parse if we don't replace spaces with dashes
String(
let userAgent = String(
format: "%@/%@.%@ (%@; %@ %@) %@/%@",
appInfo.getFormattedAppName(),
appInfo.getAppVersion(),
Expand All @@ -31,5 +31,9 @@ class ATTNUserAgentBuilder: ATTNUserAgentBuilderProtocol {
appInfo.getSdkName(),
appInfo.getSdkVersion()
)

Loggers.event.debug("Created User Agent: \(userAgent)")

return userAgent
}
}
5 changes: 5 additions & 0 deletions Sources/ATTNVisitorService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,17 @@ struct ATTNVisitorService {
return createNewVisitorId()
}

Loggers.event.info("Obtained existing visitor id: \(existingVisitorId)")

return existingVisitorId
}

func createNewVisitorId() -> String {
let newVisitorId = generateVisitorId()
persistentStorage.save(newVisitorId as NSObject, forKey: Constants.visitorIdKey)

Loggers.event.info("Generated new visitor id: \(newVisitorId)")

return newVisitorId
}

Expand Down
6 changes: 3 additions & 3 deletions Sources/Helpers/ATTNJsonUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@
import Foundation

protocol ATTNJsonUtilsProtocol {
static func convertObjectToJson(_ object: Any) throws -> String?
static func convertObjectToJson(_ object: Any, file: String, function: String) throws -> String?
}

struct ATTNJsonUtils: ATTNJsonUtilsProtocol {
private init() { }

static func convertObjectToJson(_ object: Any) throws -> String? {
static func convertObjectToJson(_ object: Any, file: String = #file, function: String = #function) throws -> String? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: object, options: [])
guard let jsonString = String(data: jsonData, encoding: .utf8) else {
NSLog("Could not encode JSON data to a string.")
Loggers.event.error("Could not encode JSON data to a string. Function:\(function), File:\(file)")
return nil
}
return jsonString
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ extension ATTNAddToCartEvent: ATTNEventRequestProvider {
var eventRequests = [ATTNEventRequest]()

if items.isEmpty {
NSLog("No items found in the AddToCart event.")
Loggers.event.debug("No items found in the AddToCart event.")
return []
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/Helpers/Extension/ATTNEvent+Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import Foundation
extension ATTNEvent {
func convertEventToRequests() -> [ATTNEventRequest] {
guard let provider = self as? ATTNEventRequestProvider else {
NSLog("ERROR: Unknown event type: \(type(of: self))")
Loggers.event.debug("Unknown event type: \(type(of: self)). It can not be converted to EventRequest.")
return []
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ extension ATTNProductViewEvent: ATTNEventRequestProvider {
var eventRequests = [ATTNEventRequest]()

if items.isEmpty {
NSLog("No items found in the ProductView event.")
Loggers.event.debug("No items found in the ProductView event.")
return []
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ extension ATTNPurchaseEvent: ATTNEventRequestProvider {
var eventRequests = [ATTNEventRequest]()

guard !items.isEmpty else {
NSLog("No items found in the purchase event.")
Loggers.event.debug("No items found in the purchase event.")
return []
}

Expand Down
1 change: 1 addition & 0 deletions Sources/Helpers/Extension/ATTNSDK+Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ extension ATTNSDK {
func initializeSkipFatigueOnCreatives() {
if let skipFatigueValue = ProcessInfo.processInfo.environment[ATTNConstants.skipFatigueEnvKey] {
self.skipFatigueOnCreative = skipFatigueValue.booleanValue
Loggers.creative.info("SKIP_FATIGUE_ON_CREATIVE: \(skipFatigueValue)")
} else {
self.skipFatigueOnCreative = false
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/Helpers/Extension/ATTNUserIdentity+Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ extension ATTNUserIdentity {
do {
return try ATTNJsonUtils.convertObjectToJson(ids) ?? "[]"
} catch {
NSLog("Could not serialize the external vendor ids. Returning an empty array. Error: '\(error.localizedDescription)'")
Loggers.event.error("Could not serialize the external vendor ids. Returning an empty array. Error: '\(error.localizedDescription)'")
return "[]"
}
}
Expand All @@ -56,7 +56,7 @@ extension ATTNUserIdentity {
do {
return try ATTNJsonUtils.convertObjectToJson(metadata) ?? "{}"
} catch {
NSLog("Could not serialize the external vendor ids. Returning an empty blob. Error: '\(error.localizedDescription)'")
Loggers.event.error("Could not serialize the external vendor ids. Returning an empty blob. Error: '\(error.localizedDescription)'")
return "{}"
}
}
Expand Down
17 changes: 17 additions & 0 deletions Sources/Helpers/Logger.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//
// Logger.swift
// attentive-ios-sdk-framework
//
// Created by Vladimir - Work on 2024-06-25.
//

import Foundation
import os

enum Loggers {
private static var subsystem: String { Bundle.main.bundleIdentifier ?? "com.attentive.attentive-ios-sdk-local" }

static var network = Logger(subsystem: subsystem, category: "network")
static var event = Logger(subsystem: subsystem, category: "event")
static var creative = Logger(subsystem: subsystem, category: "creative")
}
1 change: 1 addition & 0 deletions Sources/Public/ATTNEventTracker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public final class ATTNEventTracker: NSObject {
@objc(setupWithSdk:)
public static func setup(with sdk: ATTNSDK) {
_sharedInstance = ATTNEventTracker(sdk: sdk)
Loggers.event.debug("ATTNEventTracker was initialized with SDK")
}

@available(swift, deprecated: 0.6, message: "Please use record(event: ATTNEvent) instead.")
Expand Down
2 changes: 1 addition & 1 deletion Sources/Public/Events/ATTNCustomEvent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public final class ATTNCustomEvent: NSObject, ATTNEvent {
ATTNParameterValidation.verifyNotNil(type as NSObject, inputName: "type")
ATTNParameterValidation.verifyStringOrNil(type as NSObject, inputName: "type")
if let invalidCharInType = ATTNCustomEvent.findInvalidCharacter(in: type) {
print("Invalid character \(invalidCharInType) in CustomEvent type \(type)")
Loggers.event.debug("Invalid character \(invalidCharInType) in CustomEvent type \(type)")
return nil
}

Expand Down
Loading
Loading