From 98151c83dfb34f269b33fe3abe4c2e5d1790d185 Mon Sep 17 00:00:00 2001 From: Jerome Duquennoy Date: Tue, 23 Jan 2024 15:09:45 +0100 Subject: [PATCH 1/8] Expose publicly some types and methods related to the logging system, to allow injection of custom loggers --- Sources/Logger.swift | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Sources/Logger.swift b/Sources/Logger.swift index 6e192135..3c974ad0 100644 --- a/Sources/Logger.swift +++ b/Sources/Logger.swift @@ -10,7 +10,7 @@ import Foundation /// This defines the various levels of logging that a message may be tagged with. This allows hiding and /// showing different logging levels at run time depending on the environment -enum LogLevel: String { +public enum LogLevel: String { /// Logging displays *all* logs and additional debug information that may be useful to a developer case debug @@ -26,18 +26,18 @@ enum LogLevel: String { /// This holds all the data for each log message, since the formatting is up to each /// logging object. It is a simple bag of data -struct LogMessage { +public struct LogMessage { /// The file where this log message was created - let file: String + public let file: String /// The function where this log message was created - let function: String + public let function: String /// The text of the log message - let text: String + public let text: String /// The level of the log message - let level: LogLevel + public let level: LogLevel init(path: String, function: String, text: String, level: LogLevel) { if let file = path.components(separatedBy: "/").last { @@ -52,17 +52,17 @@ struct LogMessage { } /// Any object that conforms to this protocol may log messages -protocol Logging { +public protocol Logging { func addMessage(message: LogMessage) } -class Logger { +public class Logger { private static var loggers = [Logging]() private static var enabledLevels = Set() private static let readWriteLock: ReadWriteLock = ReadWriteLock(label: "loggerLock") /// Add a `Logging` object to receive all log messages - class func addLogging(_ logging: Logging) { + public class func addLogging(_ logging: Logging) { readWriteLock.write { loggers.append(logging) } From 348574216bd8af2bf3a1648855b22b82932da4dc Mon Sep 17 00:00:00 2001 From: Jared McFarland Date: Thu, 30 Jan 2025 12:19:36 -0800 Subject: [PATCH 2/8] rename with MP prefix to avoid namespace clashes --- .../MixpanelDemoTests/LoggerTests.swift | 46 +++++++++--------- Sources/Error.swift | 2 +- Sources/FileLogging.swift | 4 +- Sources/Flush.swift | 4 +- Sources/FlushRequest.swift | 4 +- Sources/JSONHandler.swift | 10 ++-- Sources/MPDB.swift | 30 ++++++------ Sources/{Logger.swift => MPLogger.swift} | 48 +++++++++---------- Sources/Mixpanel.swift | 4 +- Sources/MixpanelInstance.swift | 36 +++++++------- Sources/MixpanelPersistence.swift | 18 +++---- Sources/Network.swift | 4 +- Sources/PrintLogging.swift | 8 ++-- Sources/Track.swift | 6 +-- 14 files changed, 112 insertions(+), 112 deletions(-) rename Sources/{Logger.swift => MPLogger.swift} (76%) diff --git a/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift b/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift index 62867bf4..3b2c86e9 100644 --- a/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift +++ b/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift @@ -15,63 +15,63 @@ class LoggerTests: XCTestCase { func testEnableDebug() { let counter = CounterLogging() - Logger.addLogging(counter) - Logger.enableLevel(.debug) + MPLogger.addLogging(counter) + MPLogger.enableLevel(.debug) - Logger.debug(message: "logged") + MPLogger.debug(message: "logged") XCTAssertEqual(1, counter.count) } func testEnableInfo() { let counter = CounterLogging() - Logger.addLogging(counter) - Logger.enableLevel(.info) - Logger.info(message: "logged") + MPLogger.addLogging(counter) + MPLogger.enableLevel(.info) + MPLogger.info(message: "logged") XCTAssertEqual(1, counter.count) } func testEnableWarning() { let counter = CounterLogging() - Logger.addLogging(counter) - Logger.enableLevel(.warning) - Logger.warn(message: "logged") + MPLogger.addLogging(counter) + MPLogger.enableLevel(.warning) + MPLogger.warn(message: "logged") XCTAssertEqual(1, counter.count) } func testEnableError() { let counter = CounterLogging() - Logger.addLogging(counter) - Logger.enableLevel(.error) - Logger.error(message: "logged") + MPLogger.addLogging(counter) + MPLogger.enableLevel(.error) + MPLogger.error(message: "logged") XCTAssertEqual(1, counter.count) } func testDisabledLogging() { let counter = CounterLogging() - Logger.addLogging(counter) - Logger.disableLevel(.debug) - Logger.debug(message: "not logged") + MPLogger.addLogging(counter) + MPLogger.disableLevel(.debug) + MPLogger.debug(message: "not logged") XCTAssertEqual(0, counter.count) - Logger.disableLevel(.error) - Logger.error(message: "not logged") + MPLogger.disableLevel(.error) + MPLogger.error(message: "not logged") XCTAssertEqual(0, counter.count) - Logger.disableLevel(.info) - Logger.info(message: "not logged") + MPLogger.disableLevel(.info) + MPLogger.info(message: "not logged") XCTAssertEqual(0, counter.count) - Logger.disableLevel(.warning) - Logger.warn(message: "not logged") + MPLogger.disableLevel(.warning) + MPLogger.warn(message: "not logged") XCTAssertEqual(0, counter.count) } } /// This is a stub that implements `Logging` to be passed to our `Logger` instance for testing -class CounterLogging: Logging { +class CounterLogging: MPLogging { var count = 0 - func addMessage(message: LogMessage) { + func addMessage(message: MPLogMessage) { count = count + 1 } } diff --git a/Sources/Error.swift b/Sources/Error.swift index 1a5d6f1b..8046c44b 100644 --- a/Sources/Error.swift +++ b/Sources/Error.swift @@ -36,7 +36,7 @@ class ErrorHandler { class func logError(_ error: Error) { let stackSymbols = Thread.callStackSymbols - Logger.error(message: "Error: \(error) \n Stack Symbols: \(stackSymbols)") + MPLogger.error(message: "Error: \(error) \n Stack Symbols: \(stackSymbols)") } } diff --git a/Sources/FileLogging.swift b/Sources/FileLogging.swift index 868a521d..46e3d722 100644 --- a/Sources/FileLogging.swift +++ b/Sources/FileLogging.swift @@ -9,7 +9,7 @@ import Foundation /// Logs all messages to a file -class FileLogging: Logging { +class FileLogging: MPLogging { private let fileHandle: FileHandle init(path: String) { @@ -28,7 +28,7 @@ class FileLogging: Logging { fileHandle.closeFile() } - func addMessage(message: LogMessage) { + func addMessage(message: MPLogMessage) { let string = "File: \(message.file) - Func: \(message.function) - " + "Level: \(message.level.rawValue) - Message: \(message.text)" if let data = string.data(using: String.Encoding.utf8) { diff --git a/Sources/Flush.swift b/Sources/Flush.swift index a11618bb..10026095 100644 --- a/Sources/Flush.swift +++ b/Sources/Flush.swift @@ -122,8 +122,8 @@ class Flush: AppLifecycle { (entity["id"] as? Int32) ?? 0 } // Log data payload sent - Logger.debug(message: "Sending batch of data") - Logger.debug(message: batch as Any) + MPLogger.debug(message: "Sending batch of data") + MPLogger.debug(message: batch as Any) let requestData = JSONHandler.encodeAPIData(batch) if let requestData = requestData { #if os(iOS) diff --git a/Sources/FlushRequest.swift b/Sources/FlushRequest.swift index bf260364..7d8b1d5d 100644 --- a/Sources/FlushRequest.swift +++ b/Sources/FlushRequest.swift @@ -65,13 +65,13 @@ class FlushRequest: Network { failure: { (reason, _, response) in self.networkConsecutiveFailures += 1 self.updateRetryDelay(response) - Logger.warn(message: "API request to \(resource.path) has failed with reason \(reason)") + MPLogger.warn(message: "API request to \(resource.path) has failed with reason \(reason)") completion(false) }, success: { (result, response) in self.networkConsecutiveFailures = 0 self.updateRetryDelay(response) if result == 0 { - Logger.info(message: "\(base) api rejected some items") + MPLogger.info(message: "\(base) api rejected some items") } completion(true) }) diff --git a/Sources/JSONHandler.swift b/Sources/JSONHandler.swift index 78b61fc6..28dc5746 100644 --- a/Sources/JSONHandler.swift +++ b/Sources/JSONHandler.swift @@ -16,7 +16,7 @@ class JSONHandler { let data: Data? = serializeJSONObject(obj) guard let d = data else { - Logger.warn(message: "couldn't serialize object") + MPLogger.warn(message: "couldn't serialize object") return nil } @@ -28,7 +28,7 @@ class JSONHandler { do { object = try JSONSerialization.jsonObject(with: data, options: []) } catch { - Logger.warn(message: "exception decoding object data") + MPLogger.warn(message: "exception decoding object data") } return object } @@ -44,7 +44,7 @@ class JSONHandler { } guard JSONSerialization.isValidJSONObject(serializableJSONObject) else { - Logger.warn(message: "object isn't valid and can't be serialzed to JSON") + MPLogger.warn(message: "object isn't valid and can't be serialzed to JSON") return nil } @@ -53,7 +53,7 @@ class JSONHandler { serializedObject = try JSONSerialization .data(withJSONObject: serializableJSONObject, options: []) } catch { - Logger.warn(message: "exception encoding api data") + MPLogger.warn(message: "exception encoding api data") } return serializedObject } @@ -110,7 +110,7 @@ class JSONHandler { // all nil properties outside of Arrays are converted to NSNull() return NSNull() } else { - Logger.info(message: "enforcing string on object") + MPLogger.info(message: "enforcing string on object") return objString } } diff --git a/Sources/MPDB.swift b/Sources/MPDB.swift index e5ab9e65..aea93578 100644 --- a/Sources/MPDB.swift +++ b/Sources/MPDB.swift @@ -45,13 +45,13 @@ class MPDB { } private func reconnect() { - Logger.warn(message: "No database connection found. Calling MPDB.open()") + MPLogger.warn(message: "No database connection found. Calling MPDB.open()") open() } func open() { if apiToken.isEmpty { - Logger.error(message: "Project token must not be empty. Database cannot be opened.") + MPLogger.error(message: "Project token must not be empty. Database cannot be opened.") return } if let dbPath = pathToDb() { @@ -59,14 +59,14 @@ class MPDB { logSqlError(message: "Error opening or creating database at path: \(dbPath)") close() } else { - Logger.info(message: "Successfully opened connection to database at path: \(dbPath)") + MPLogger.info(message: "Successfully opened connection to database at path: \(dbPath)") if let db = connection { let pragmaString = "PRAGMA journal_mode=WAL;" var pragmaStatement: OpaquePointer? if sqlite3_prepare_v2(db, pragmaString, -1, &pragmaStatement, nil) == SQLITE_OK { if sqlite3_step(pragmaStatement) == SQLITE_ROW { let res = String(cString: sqlite3_column_text(pragmaStatement, 0)) - Logger.info(message: "SQLite journal mode set to \(res)") + MPLogger.info(message: "SQLite journal mode set to \(res)") } else { logSqlError(message: "Failed to enable journal_mode=WAL") } @@ -85,7 +85,7 @@ class MPDB { func close() { sqlite3_close(connection) connection = nil - Logger.info(message: "Connection to database closed.") + MPLogger.info(message: "Connection to database closed.") } private func recreate() { @@ -95,10 +95,10 @@ class MPDB { let manager = FileManager.default if manager.fileExists(atPath: dbPath) { try manager.removeItem(atPath: dbPath) - Logger.info(message: "Deleted database file at path: \(dbPath)") + MPLogger.info(message: "Deleted database file at path: \(dbPath)") } } catch let error { - Logger.error(message: "Unable to remove database file at path: \(dbPath), error: \(error)") + MPLogger.error(message: "Unable to remove database file at path: \(dbPath), error: \(error)") } } reconnect() @@ -112,7 +112,7 @@ class MPDB { var createTableStatement: OpaquePointer? if sqlite3_prepare_v2(db, createTableString, -1, &createTableStatement, nil) == SQLITE_OK { if sqlite3_step(createTableStatement) == SQLITE_DONE { - Logger.info(message: "\(tableName) table created") + MPLogger.info(message: "\(tableName) table created") } else { logSqlError(message: "\(tableName) table create failed") } @@ -133,7 +133,7 @@ class MPDB { var createIndexStatement: OpaquePointer? if sqlite3_prepare_v2(db, createIndexString, -1, &createIndexStatement, nil) == SQLITE_OK { if sqlite3_step(createIndexStatement) == SQLITE_DONE { - Logger.info(message: "\(indexName) index created") + MPLogger.info(message: "\(indexName) index created") } else { logSqlError(message: "\(indexName) index creation failed") } @@ -167,7 +167,7 @@ class MPDB { sqlite3_bind_int(insertStatement, 2, flag ? 1 : 0) sqlite3_bind_double(insertStatement, 3, Date().timeIntervalSince1970) if sqlite3_step(insertStatement) == SQLITE_DONE { - Logger.info(message: "Successfully inserted row into table \(tableName)") + MPLogger.info(message: "Successfully inserted row into table \(tableName)") } else { logSqlError(message: "Failed to insert row into table \(tableName)") recreate() @@ -191,7 +191,7 @@ class MPDB { var deleteStatement: OpaquePointer? if sqlite3_prepare_v2(db, deleteString, -1, &deleteStatement, nil) == SQLITE_OK { if sqlite3_step(deleteStatement) == SQLITE_DONE { - Logger.info(message: "Successfully deleted rows from table \(tableName)") + MPLogger.info(message: "Successfully deleted rows from table \(tableName)") } else { logSqlError(message: "Failed to delete rows from table \(tableName)") recreate() @@ -223,7 +223,7 @@ class MPDB { var updateStatement: OpaquePointer? if sqlite3_prepare_v2(db, updateString, -1, &updateStatement, nil) == SQLITE_OK { if sqlite3_step(updateStatement) == SQLITE_DONE { - Logger.info(message: "Successfully updated rows from table \(tableName)") + MPLogger.info(message: "Successfully updated rows from table \(tableName)") } else { logSqlError(message: "Failed to update rows from table \(tableName)") recreate() @@ -266,7 +266,7 @@ class MPDB { } } if rowsRead > 0 { - Logger.info(message: "Successfully read \(rowsRead) from table \(tableName)") + MPLogger.info(message: "Successfully read \(rowsRead) from table \(tableName)") } } else { logSqlError(message: "SELECT statement for table \(tableName) could not be prepared") @@ -281,10 +281,10 @@ class MPDB { private func logSqlError(message: String? = nil) { if let db = connection { if let msg = message { - Logger.error(message: msg) + MPLogger.error(message: msg) } let sqlError = String(cString: sqlite3_errmsg(db)!) - Logger.error(message: sqlError) + MPLogger.error(message: sqlError) } else { reconnect() } diff --git a/Sources/Logger.swift b/Sources/MPLogger.swift similarity index 76% rename from Sources/Logger.swift rename to Sources/MPLogger.swift index 3c974ad0..32cecfc1 100644 --- a/Sources/Logger.swift +++ b/Sources/MPLogger.swift @@ -1,5 +1,5 @@ // -// Logger.swift +// MPLogger.swift // Logger // // Created by Sam Green on 7/8/16. @@ -10,7 +10,7 @@ import Foundation /// This defines the various levels of logging that a message may be tagged with. This allows hiding and /// showing different logging levels at run time depending on the environment -public enum LogLevel: String { +public enum MPLogLevel: String { /// Logging displays *all* logs and additional debug information that may be useful to a developer case debug @@ -26,7 +26,7 @@ public enum LogLevel: String { /// This holds all the data for each log message, since the formatting is up to each /// logging object. It is a simple bag of data -public struct LogMessage { +public struct MPLogMessage { /// The file where this log message was created public let file: String @@ -37,9 +37,9 @@ public struct LogMessage { public let text: String /// The level of the log message - public let level: LogLevel + public let level: MPLogLevel - init(path: String, function: String, text: String, level: LogLevel) { + init(path: String, function: String, text: String, level: MPLogLevel) { if let file = path.components(separatedBy: "/").last { self.file = file } else { @@ -52,31 +52,31 @@ public struct LogMessage { } /// Any object that conforms to this protocol may log messages -public protocol Logging { - func addMessage(message: LogMessage) +public protocol MPLogging { + func addMessage(message: MPLogMessage) } -public class Logger { - private static var loggers = [Logging]() - private static var enabledLevels = Set() - private static let readWriteLock: ReadWriteLock = ReadWriteLock(label: "loggerLock") +public class MPLogger { + private static var loggers = [MPLogging]() + private static var enabledLevels = Set() + private static let readWriteLock: ReadWriteLock = ReadWriteLock(label: "mpLoggerLock") /// Add a `Logging` object to receive all log messages - public class func addLogging(_ logging: Logging) { + public class func addLogging(_ logging: MPLogging) { readWriteLock.write { loggers.append(logging) } } /// Enable log messages of a specific `LogLevel` to be added to the log - class func enableLevel(_ level: LogLevel) { + class func enableLevel(_ level: MPLogLevel) { readWriteLock.write { enabledLevels.insert(level) } } /// Disable log messages of a specific `LogLevel` to prevent them from being logged - class func disableLevel(_ level: LogLevel) { + class func disableLevel(_ level: MPLogLevel) { readWriteLock.write { enabledLevels.remove(level) } @@ -85,55 +85,55 @@ public class Logger { /// debug: Adds a debug message to the Mixpanel log /// - Parameter message: The message to be added to the log class func debug(message: @autoclosure() -> Any, _ path: String = #file, _ function: String = #function) { - var enabledLevels = Set() + var enabledLevels = Set() readWriteLock.read { enabledLevels = self.enabledLevels } guard enabledLevels.contains(.debug) else { return } - forwardLogMessage(LogMessage(path: path, function: function, text: "\(message())", + forwardLogMessage(MPLogMessage(path: path, function: function, text: "\(message())", level: .debug)) } /// info: Adds an informational message to the Mixpanel log /// - Parameter message: The message to be added to the log class func info(message: @autoclosure() -> Any, _ path: String = #file, _ function: String = #function) { - var enabledLevels = Set() + var enabledLevels = Set() readWriteLock.read { enabledLevels = self.enabledLevels } guard enabledLevels.contains(.info) else { return } - forwardLogMessage(LogMessage(path: path, function: function, text: "\(message())", + forwardLogMessage(MPLogMessage(path: path, function: function, text: "\(message())", level: .info)) } /// warn: Adds a warning message to the Mixpanel log /// - Parameter message: The message to be added to the log class func warn(message: @autoclosure() -> Any, _ path: String = #file, _ function: String = #function) { - var enabledLevels = Set() + var enabledLevels = Set() readWriteLock.read { enabledLevels = self.enabledLevels } guard enabledLevels.contains(.warning) else { return } - forwardLogMessage(LogMessage(path: path, function: function, text: "\(message())", + forwardLogMessage(MPLogMessage(path: path, function: function, text: "\(message())", level: .warning)) } /// error: Adds an error message to the Mixpanel log /// - Parameter message: The message to be added to the log class func error(message: @autoclosure() -> Any, _ path: String = #file, _ function: String = #function) { - var enabledLevels = Set() + var enabledLevels = Set() readWriteLock.read { enabledLevels = self.enabledLevels } guard enabledLevels.contains(.error) else { return } - forwardLogMessage(LogMessage(path: path, function: function, text: "\(message())", + forwardLogMessage(MPLogMessage(path: path, function: function, text: "\(message())", level: .error)) } /// This forwards a `LogMessage` to each logger that has been added - class private func forwardLogMessage(_ message: LogMessage) { + class private func forwardLogMessage(_ message: MPLogMessage) { // Forward the log message to every registered Logging instance - var loggers = [Logging]() + var loggers = [MPLogging]() readWriteLock.read { loggers = self.loggers } diff --git a/Sources/Mixpanel.swift b/Sources/Mixpanel.swift index 0c5f4766..e5e3b674 100644 --- a/Sources/Mixpanel.swift +++ b/Sources/Mixpanel.swift @@ -248,7 +248,7 @@ final class MixpanelManager { init() { instances = [String: MixpanelInstance]() - Logger.addLogging(PrintLogging()) + MPLogger.addLogging(PrintLogging()) readWriteLock = ReadWriteLock(label: "com.mixpanel.instance.manager.lock") instanceQueue = DispatchQueue(label: "com.mixpanel.instance.manager.instance", qos: .utility, autoreleaseFrequency: .workItem) } @@ -318,7 +318,7 @@ final class MixpanelManager { instance = instances[instanceName] } if instance == nil { - Logger.warn(message: "no such instance: \(instanceName)") + MPLogger.warn(message: "no such instance: \(instanceName)") return nil } return instance diff --git a/Sources/MixpanelInstance.swift b/Sources/MixpanelInstance.swift index bda85a8f..cf3acf4f 100644 --- a/Sources/MixpanelInstance.swift +++ b/Sources/MixpanelInstance.swift @@ -188,17 +188,17 @@ open class MixpanelInstance: CustomDebugStringConvertible, FlushDelegate, AEDele open var loggingEnabled: Bool = false { didSet { if loggingEnabled { - Logger.enableLevel(.debug) - Logger.enableLevel(.info) - Logger.enableLevel(.warning) - Logger.enableLevel(.error) - Logger.info(message: "Logging Enabled") + MPLogger.enableLevel(.debug) + MPLogger.enableLevel(.info) + MPLogger.enableLevel(.warning) + MPLogger.enableLevel(.error) + MPLogger.info(message: "Logging Enabled") } else { - Logger.info(message: "Logging Disabled") - Logger.disableLevel(.debug) - Logger.disableLevel(.info) - Logger.disableLevel(.warning) - Logger.disableLevel(.error) + MPLogger.info(message: "Logging Disabled") + MPLogger.disableLevel(.debug) + MPLogger.disableLevel(.info) + MPLogger.disableLevel(.warning) + MPLogger.disableLevel(.error) } #if DEBUG var trackProps: Properties = ["Logging Enabled": loggingEnabled] @@ -351,7 +351,7 @@ open class MixpanelInstance: CustomDebugStringConvertible, FlushDelegate, AEDele AutomaticProperties.automaticPropertiesLock.write { AutomaticProperties.properties["$wifi"] = wifi } - Logger.info(message: "reachability changed, wifi=\(wifi)") + MPLogger.info(message: "reachability changed, wifi=\(wifi)") } if SCNetworkReachabilitySetCallback(reachability, reachabilityCallback, &context) { if !SCNetworkReachabilitySetDispatchQueue(reachability, trackingQueue) { @@ -456,10 +456,10 @@ open class MixpanelInstance: CustomDebugStringConvertible, FlushDelegate, AEDele #if os(iOS) && !os(watchOS) && !targetEnvironment(macCatalyst) if let reachability = MixpanelInstance.reachability { if !SCNetworkReachabilitySetCallback(reachability, nil, nil) { - Logger.error(message: "\(self) error unsetting reachability callback") + MPLogger.error(message: "\(self) error unsetting reachability callback") } if !SCNetworkReachabilitySetDispatchQueue(reachability, nil) { - Logger.error(message: "\(self) error unsetting reachability dispatch queue") + MPLogger.error(message: "\(self) error unsetting reachability dispatch queue") } } #endif @@ -701,7 +701,7 @@ extension MixpanelInstance { return } if distinctId.isEmpty { - Logger.error(message: "\(self) cannot identify blank distinct id") + MPLogger.error(message: "\(self) cannot identify blank distinct id") if let completion = completion { DispatchQueue.main.async(execute: completion) } @@ -791,7 +791,7 @@ extension MixpanelInstance { } if distinctId.isEmpty { - Logger.error(message: "\(self) cannot identify blank distinct id") + MPLogger.error(message: "\(self) cannot identify blank distinct id") if let completion = completion { DispatchQueue.main.async(execute: completion) } @@ -799,7 +799,7 @@ extension MixpanelInstance { } if alias.isEmpty { - Logger.error(message: "\(self) create alias called with empty alias") + MPLogger.error(message: "\(self) create alias called with empty alias") if let completion = completion { DispatchQueue.main.async(execute: completion) } @@ -850,7 +850,7 @@ extension MixpanelInstance { } flush(completion: completion) } else { - Logger.error(message: "alias: \(alias) matches distinctId: \(distinctId) - skipping api call.") + MPLogger.error(message: "alias: \(alias) matches distinctId: \(distinctId) - skipping api call.") if let completion = completion { DispatchQueue.main.async(execute: completion) } @@ -1159,7 +1159,7 @@ extension MixpanelInstance { if !(group.groupKey == groupKey && group.groupID.equals(rhs: groupID)) { // we somehow hit a collision on the map key, return a new group with the correct key and ID - Logger.info(message: "groups dictionary key collision: \(key)") + MPLogger.info(message: "groups dictionary key collision: \(key)") let newGroup = Group(apiToken: apiToken, serialQueue: trackingQueue, lock: self.readWriteLock, diff --git a/Sources/MixpanelPersistence.swift b/Sources/MixpanelPersistence.swift index c6a6a1b0..61a081a2 100644 --- a/Sources/MixpanelPersistence.swift +++ b/Sources/MixpanelPersistence.swift @@ -139,7 +139,7 @@ class MixpanelPersistence { defaults.set(timedEventsData, forKey: "\(prefix)\(MixpanelUserDefaultsKeys.timedEvents)") defaults.synchronize() } catch { - Logger.warn(message: "Failed to archive timed events") + MPLogger.warn(message: "Failed to archive timed events") } } @@ -154,7 +154,7 @@ class MixpanelPersistence { do { return try NSKeyedUnarchiver.unarchivedObject(ofClasses: archivedClasses, from: timedEventsData) as? InternalProperties ?? InternalProperties() } catch { - Logger.warn(message: "Failed to unarchive timed events") + MPLogger.warn(message: "Failed to unarchive timed events") return InternalProperties() } } @@ -169,7 +169,7 @@ class MixpanelPersistence { defaults.set(superPropertiesData, forKey: "\(prefix)\(MixpanelUserDefaultsKeys.superProperties)") defaults.synchronize() } catch { - Logger.warn(message: "Failed to archive super properties") + MPLogger.warn(message: "Failed to archive super properties") } } @@ -184,7 +184,7 @@ class MixpanelPersistence { do { return try NSKeyedUnarchiver.unarchivedObject(ofClasses: archivedClasses, from: superPropertiesData) as? InternalProperties ?? InternalProperties() } catch { - Logger.warn(message: "Failed to unarchive super properties") + MPLogger.warn(message: "Failed to unarchive super properties") return InternalProperties() } } @@ -355,14 +355,14 @@ class MixpanelPersistence { if #available(iOS 11.0, macOS 10.13, watchOS 4.0, tvOS 11.0, *) { guard let data = try? Data(contentsOf: URL(fileURLWithPath: filePath)), let unarchivedData = try? NSKeyedUnarchiver.unarchivedObject(ofClasses: MixpanelPersistence.archivedClasses, from: data) else { - Logger.info(message: "Unable to read file at path: \(filePath)") + MPLogger.info(message: "Unable to read file at path: \(filePath)") removeArchivedFile(atPath: filePath) return nil } return unarchivedData } else { guard let unarchivedData = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) else { - Logger.info(message: "Unable to read file at path: \(filePath)") + MPLogger.info(message: "Unable to read file at path: \(filePath)") removeArchivedFile(atPath: filePath) return nil } @@ -374,7 +374,7 @@ class MixpanelPersistence { do { try FileManager.default.removeItem(atPath: filePath) } catch let err { - Logger.info(message: "Unable to remove file at path: \(filePath), error: \(err)") + MPLogger.info(message: "Unable to remove file at path: \(filePath), error: \(err)") } } @@ -440,12 +440,12 @@ class MixpanelPersistence { private func unarchiveWithType(_ type: String) -> Any? { let filePath = filePathWithType(type) guard let path = filePath else { - Logger.info(message: "bad file path, cant fetch file") + MPLogger.info(message: "bad file path, cant fetch file") return nil } guard let unarchivedData = unarchiveWithFilePath(path) else { - Logger.info(message: "can't unarchive file") + MPLogger.info(message: "can't unarchive file") return nil } diff --git a/Sources/Network.swift b/Sources/Network.swift index f4620144..3d5fba0f 100644 --- a/Sources/Network.swift +++ b/Sources/Network.swift @@ -107,8 +107,8 @@ class Network { return nil } - Logger.debug(message: "Fetching URL") - Logger.debug(message: url.absoluteURL) + MPLogger.debug(message: "Fetching URL") + MPLogger.debug(message: url.absoluteURL) var request = URLRequest(url: url) request.httpMethod = resource.method.rawValue request.httpBody = resource.requestBody diff --git a/Sources/PrintLogging.swift b/Sources/PrintLogging.swift index b1c8d4a9..732c27d5 100644 --- a/Sources/PrintLogging.swift +++ b/Sources/PrintLogging.swift @@ -9,16 +9,16 @@ import Foundation /// Simply formats and prints the object by calling `print` -class PrintLogging: Logging { - func addMessage(message: LogMessage) { +class PrintLogging: MPLogging { + func addMessage(message: MPLogMessage) { print("[Mixpanel - \(message.file) - func \(message.function)] (\(message.level.rawValue)) - \(message.text)") } } /// Simply formats and prints the object by calling `debugPrint`, this makes things a bit easier if you /// need to print data that may be quoted for instance. -class PrintDebugLogging: Logging { - func addMessage(message: LogMessage) { +class PrintDebugLogging: MPLogging { + func addMessage(message: MPLogMessage) { debugPrint("[Mixpanel - \(message.file) - func \(message.function)] (\(message.level.rawValue)) - \(message.text)") } } diff --git a/Sources/Track.swift b/Sources/Track.swift index ffc64143..eeb445eb 100644 --- a/Sources/Track.swift +++ b/Sources/Track.swift @@ -41,7 +41,7 @@ class Track { if let event = event { ev = event } else { - Logger.info(message: "mixpanel track called with empty event parameter. using 'mp_event'") + MPLogger.info(message: "mixpanel track called with empty event parameter. using 'mp_event'") } if !(mixpanelInstance?.trackAutomaticEventsEnabled ?? false) && ev.hasPrefix("$ae_") { return timedEvents @@ -140,7 +140,7 @@ class Track { } var updatedTimedEvents = timedEvents guard let event = event, !event.isEmpty else { - Logger.error(message: "mixpanel cannot time an empty event") + MPLogger.error(message: "mixpanel cannot time an empty event") return updatedTimedEvents } updatedTimedEvents[event] = startTime @@ -156,7 +156,7 @@ class Track { func clearTimedEvent(event: String?, timedEvents: InternalProperties) -> InternalProperties { var updatedTimedEvents = timedEvents guard let event = event, !event.isEmpty else { - Logger.error(message: "mixpanel cannot clear an empty timed event") + MPLogger.error(message: "mixpanel cannot clear an empty timed event") return updatedTimedEvents } updatedTimedEvents.removeValue(forKey: event) From 27ce7860d06ce05985d66e1e0005c72097c3f3b7 Mon Sep 17 00:00:00 2001 From: Jared McFarland Date: Thu, 30 Jan 2025 12:26:16 -0800 Subject: [PATCH 3/8] fix project file --- Mixpanel.xcodeproj/project.pbxproj | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Mixpanel.xcodeproj/project.pbxproj b/Mixpanel.xcodeproj/project.pbxproj index 17a24ac8..d59e5950 100644 --- a/Mixpanel.xcodeproj/project.pbxproj +++ b/Mixpanel.xcodeproj/project.pbxproj @@ -11,7 +11,10 @@ 17C6547B2BB1F16000C8A126 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 1728208D2BA8BDE4002CD973 /* PrivacyInfo.xcprivacy */; }; 17C6547C2BB1F16400C8A126 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 1728208D2BA8BDE4002CD973 /* PrivacyInfo.xcprivacy */; }; 17C6547D2BB1F16800C8A126 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 1728208D2BA8BDE4002CD973 /* PrivacyInfo.xcprivacy */; }; - 51DD567C1D306B740045D3DB /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* Logger.swift */; }; + 17C9D9082D4C170C008F04BB /* MPLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17C9D9072D4C170C008F04BB /* MPLogger.swift */; }; + 17C9D9092D4C170C008F04BB /* MPLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17C9D9072D4C170C008F04BB /* MPLogger.swift */; }; + 17C9D90A2D4C170C008F04BB /* MPLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17C9D9072D4C170C008F04BB /* MPLogger.swift */; }; + 17C9D90B2D4C170C008F04BB /* MPLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17C9D9072D4C170C008F04BB /* MPLogger.swift */; }; 51DD56831D306B7B0045D3DB /* PrintLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56801D306B7B0045D3DB /* PrintLogging.swift */; }; 51DD56841D306B7B0045D3DB /* FileLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56811D306B7B0045D3DB /* FileLogging.swift */; }; 673ABE3A21360CBE00B1784B /* Group.swift in Sources */ = {isa = PBXBuildFile; fileRef = 673ABE3921360CBE00B1784B /* Group.swift */; }; @@ -28,7 +31,6 @@ 86F86EB7224439D300B69832 /* Mixpanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = E115948A1CFF1538007F8B4F /* Mixpanel.swift */; }; 86F86EB8224439D300B69832 /* MixpanelInstance.swift in Sources */ = {isa = PBXBuildFile; fileRef = E115948D1D000709007F8B4F /* MixpanelInstance.swift */; }; 86F86EB9224439DC00B69832 /* AutomaticProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1D335CF1D3059A800E68E12 /* AutomaticProperties.swift */; }; - 86F86EBA224439E300B69832 /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* Logger.swift */; }; 86F86EBB224439EB00B69832 /* FlushRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1D335CB1D303A0D00E68E12 /* FlushRequest.swift */; }; 86F86EBC224439F100B69832 /* PrintLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56801D306B7B0045D3DB /* PrintLogging.swift */; }; 86F86EBD224439F500B69832 /* Flush.swift in Sources */ = {isa = PBXBuildFile; fileRef = E115949E1D01BE14007F8B4F /* Flush.swift */; }; @@ -55,7 +57,6 @@ E11594A11D01C597007F8B4F /* Track.swift in Sources */ = {isa = PBXBuildFile; fileRef = E11594A01D01C597007F8B4F /* Track.swift */; }; E12782BB1D4AB5CB0025FB05 /* PrintLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56801D306B7B0045D3DB /* PrintLogging.swift */; }; E12782BC1D4AB5CB0025FB05 /* FileLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56811D306B7B0045D3DB /* FileLogging.swift */; }; - E12782BD1D4AB5CB0025FB05 /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* Logger.swift */; }; E12782BE1D4AB5CB0025FB05 /* Mixpanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = E115948A1CFF1538007F8B4F /* Mixpanel.swift */; }; E12782BF1D4AB5CB0025FB05 /* MixpanelInstance.swift in Sources */ = {isa = PBXBuildFile; fileRef = E115948D1D000709007F8B4F /* MixpanelInstance.swift */; }; E12782C11D4AB5CB0025FB05 /* Network.swift in Sources */ = {isa = PBXBuildFile; fileRef = E11594961D006022007F8B4F /* Network.swift */; }; @@ -85,7 +86,6 @@ E1F15FD61E64B5FC00391AE3 /* FlushRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1D335CB1D303A0D00E68E12 /* FlushRequest.swift */; }; E1F15FD71E64B60200391AE3 /* PrintLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56801D306B7B0045D3DB /* PrintLogging.swift */; }; E1F15FD81E64B60200391AE3 /* FileLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56811D306B7B0045D3DB /* FileLogging.swift */; }; - E1F15FD91E64B60600391AE3 /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* Logger.swift */; }; E1F15FDA1E64B60A00391AE3 /* JSONHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = E11594981D01689F007F8B4F /* JSONHandler.swift */; }; E1F15FDB1E64B60A00391AE3 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1982BFE1D0AC2E2006B7330 /* Error.swift */; }; E1F15FDC1E64B60A00391AE3 /* AutomaticProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1D335CF1D3059A800E68E12 /* AutomaticProperties.swift */; }; @@ -100,7 +100,7 @@ /* Begin PBXFileReference section */ 1728208D2BA8BDE4002CD973 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; name = PrivacyInfo.xcprivacy; path = Sources/Mixpanel/PrivacyInfo.xcprivacy; sourceTree = SOURCE_ROOT; }; - 51DD56791D306B740045D3DB /* Logger.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Logger.swift; sourceTree = ""; }; + 17C9D9072D4C170C008F04BB /* MPLogger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MPLogger.swift; sourceTree = ""; }; 51DD56801D306B7B0045D3DB /* PrintLogging.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrintLogging.swift; sourceTree = ""; }; 51DD56811D306B7B0045D3DB /* FileLogging.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileLogging.swift; sourceTree = ""; }; 673ABE3921360CBE00B1784B /* Group.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Group.swift; sourceTree = ""; }; @@ -173,8 +173,8 @@ 51DD56771D306B620045D3DB /* Log */ = { isa = PBXGroup; children = ( + 17C9D9072D4C170C008F04BB /* MPLogger.swift */, 51DD56781D306B6B0045D3DB /* Logging */, - 51DD56791D306B740045D3DB /* Logger.swift */, ); name = Log; sourceTree = ""; @@ -479,6 +479,7 @@ 86F86EF7224554B900B69832 /* Group.swift in Sources */, 86F86ECA22443A4C00B69832 /* SessionMetadata.swift in Sources */, 86F86EC922443A4700B69832 /* Constants.swift in Sources */, + 17C9D90A2D4C170C008F04BB /* MPLogger.swift in Sources */, 86F86EC722443A3C00B69832 /* FileLogging.swift in Sources */, 86F86EC622443A3100B69832 /* Error.swift in Sources */, 86F86EC522443A2C00B69832 /* People.swift in Sources */, @@ -492,7 +493,6 @@ 86F86EBC224439F100B69832 /* PrintLogging.swift in Sources */, 868550AF2699096F001FCDDC /* MixpanelPersistence.swift in Sources */, 86F86EBB224439EB00B69832 /* FlushRequest.swift in Sources */, - 86F86EBA224439E300B69832 /* Logger.swift in Sources */, 86F86EB9224439DC00B69832 /* AutomaticProperties.swift in Sources */, 86F86F3722497F2900B69832 /* AutomaticEvents.swift in Sources */, 86F86EB7224439D300B69832 /* Mixpanel.swift in Sources */, @@ -514,8 +514,8 @@ 673ABE3A21360CBE00B1784B /* Group.swift in Sources */, E11594A11D01C597007F8B4F /* Track.swift in Sources */, E11594991D01689F007F8B4F /* JSONHandler.swift in Sources */, + 17C9D9092D4C170C008F04BB /* MPLogger.swift in Sources */, E1D335D01D3059A800E68E12 /* AutomaticProperties.swift in Sources */, - 51DD567C1D306B740045D3DB /* Logger.swift in Sources */, E165228F1D6781DF000D5949 /* MixpanelType.swift in Sources */, BB9614171F3BB87700C3EF3E /* ReadWriteLock.swift in Sources */, E190522D1F9FC1BC00900E5D /* SessionMetadata.swift in Sources */, @@ -535,7 +535,7 @@ 67FF65E521878416005161FA /* Group.swift in Sources */, E12782BB1D4AB5CB0025FB05 /* PrintLogging.swift in Sources */, E12782BC1D4AB5CB0025FB05 /* FileLogging.swift in Sources */, - E12782BD1D4AB5CB0025FB05 /* Logger.swift in Sources */, + 17C9D9082D4C170C008F04BB /* MPLogger.swift in Sources */, E12782BE1D4AB5CB0025FB05 /* Mixpanel.swift in Sources */, E12782BF1D4AB5CB0025FB05 /* MixpanelInstance.swift in Sources */, E12782C11D4AB5CB0025FB05 /* Network.swift in Sources */, @@ -563,8 +563,8 @@ 67FF65E421878414005161FA /* Group.swift in Sources */, E1F15FE01E64B60D00391AE3 /* MixpanelInstance.swift in Sources */, E1F15FDF1E64B60D00391AE3 /* Mixpanel.swift in Sources */, + 17C9D90B2D4C170C008F04BB /* MPLogger.swift in Sources */, E1F15FDC1E64B60A00391AE3 /* AutomaticProperties.swift in Sources */, - E1F15FD91E64B60600391AE3 /* Logger.swift in Sources */, E1F15FD61E64B5FC00391AE3 /* FlushRequest.swift in Sources */, E1F15FD71E64B60200391AE3 /* PrintLogging.swift in Sources */, 8625BEBD26D045CE0009BAA9 /* MPDB.swift in Sources */, From 4b58a6cb7fb94768ec677d964bdfb9cb649f2980 Mon Sep 17 00:00:00 2001 From: Jared McFarland Date: Thu, 30 Jan 2025 12:38:50 -0800 Subject: [PATCH 4/8] Revert "rename with MP prefix to avoid namespace clashes" This reverts commit 348574216bd8af2bf3a1648855b22b82932da4dc. --- Mixpanel.xcodeproj/project.pbxproj | 20 ++++---- .../MixpanelDemoTests/LoggerTests.swift | 46 +++++++++--------- Sources/Error.swift | 2 +- Sources/FileLogging.swift | 4 +- Sources/Flush.swift | 4 +- Sources/FlushRequest.swift | 4 +- Sources/JSONHandler.swift | 10 ++-- Sources/{MPLogger.swift => Logger.swift} | 48 +++++++++---------- Sources/MPDB.swift | 30 ++++++------ Sources/Mixpanel.swift | 4 +- Sources/MixpanelInstance.swift | 36 +++++++------- Sources/MixpanelPersistence.swift | 18 +++---- Sources/Network.swift | 4 +- Sources/PrintLogging.swift | 8 ++-- Sources/Track.swift | 6 +-- 15 files changed, 122 insertions(+), 122 deletions(-) rename Sources/{MPLogger.swift => Logger.swift} (76%) diff --git a/Mixpanel.xcodeproj/project.pbxproj b/Mixpanel.xcodeproj/project.pbxproj index d59e5950..17a24ac8 100644 --- a/Mixpanel.xcodeproj/project.pbxproj +++ b/Mixpanel.xcodeproj/project.pbxproj @@ -11,10 +11,7 @@ 17C6547B2BB1F16000C8A126 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 1728208D2BA8BDE4002CD973 /* PrivacyInfo.xcprivacy */; }; 17C6547C2BB1F16400C8A126 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 1728208D2BA8BDE4002CD973 /* PrivacyInfo.xcprivacy */; }; 17C6547D2BB1F16800C8A126 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 1728208D2BA8BDE4002CD973 /* PrivacyInfo.xcprivacy */; }; - 17C9D9082D4C170C008F04BB /* MPLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17C9D9072D4C170C008F04BB /* MPLogger.swift */; }; - 17C9D9092D4C170C008F04BB /* MPLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17C9D9072D4C170C008F04BB /* MPLogger.swift */; }; - 17C9D90A2D4C170C008F04BB /* MPLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17C9D9072D4C170C008F04BB /* MPLogger.swift */; }; - 17C9D90B2D4C170C008F04BB /* MPLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17C9D9072D4C170C008F04BB /* MPLogger.swift */; }; + 51DD567C1D306B740045D3DB /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* Logger.swift */; }; 51DD56831D306B7B0045D3DB /* PrintLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56801D306B7B0045D3DB /* PrintLogging.swift */; }; 51DD56841D306B7B0045D3DB /* FileLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56811D306B7B0045D3DB /* FileLogging.swift */; }; 673ABE3A21360CBE00B1784B /* Group.swift in Sources */ = {isa = PBXBuildFile; fileRef = 673ABE3921360CBE00B1784B /* Group.swift */; }; @@ -31,6 +28,7 @@ 86F86EB7224439D300B69832 /* Mixpanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = E115948A1CFF1538007F8B4F /* Mixpanel.swift */; }; 86F86EB8224439D300B69832 /* MixpanelInstance.swift in Sources */ = {isa = PBXBuildFile; fileRef = E115948D1D000709007F8B4F /* MixpanelInstance.swift */; }; 86F86EB9224439DC00B69832 /* AutomaticProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1D335CF1D3059A800E68E12 /* AutomaticProperties.swift */; }; + 86F86EBA224439E300B69832 /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* Logger.swift */; }; 86F86EBB224439EB00B69832 /* FlushRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1D335CB1D303A0D00E68E12 /* FlushRequest.swift */; }; 86F86EBC224439F100B69832 /* PrintLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56801D306B7B0045D3DB /* PrintLogging.swift */; }; 86F86EBD224439F500B69832 /* Flush.swift in Sources */ = {isa = PBXBuildFile; fileRef = E115949E1D01BE14007F8B4F /* Flush.swift */; }; @@ -57,6 +55,7 @@ E11594A11D01C597007F8B4F /* Track.swift in Sources */ = {isa = PBXBuildFile; fileRef = E11594A01D01C597007F8B4F /* Track.swift */; }; E12782BB1D4AB5CB0025FB05 /* PrintLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56801D306B7B0045D3DB /* PrintLogging.swift */; }; E12782BC1D4AB5CB0025FB05 /* FileLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56811D306B7B0045D3DB /* FileLogging.swift */; }; + E12782BD1D4AB5CB0025FB05 /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* Logger.swift */; }; E12782BE1D4AB5CB0025FB05 /* Mixpanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = E115948A1CFF1538007F8B4F /* Mixpanel.swift */; }; E12782BF1D4AB5CB0025FB05 /* MixpanelInstance.swift in Sources */ = {isa = PBXBuildFile; fileRef = E115948D1D000709007F8B4F /* MixpanelInstance.swift */; }; E12782C11D4AB5CB0025FB05 /* Network.swift in Sources */ = {isa = PBXBuildFile; fileRef = E11594961D006022007F8B4F /* Network.swift */; }; @@ -86,6 +85,7 @@ E1F15FD61E64B5FC00391AE3 /* FlushRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1D335CB1D303A0D00E68E12 /* FlushRequest.swift */; }; E1F15FD71E64B60200391AE3 /* PrintLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56801D306B7B0045D3DB /* PrintLogging.swift */; }; E1F15FD81E64B60200391AE3 /* FileLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56811D306B7B0045D3DB /* FileLogging.swift */; }; + E1F15FD91E64B60600391AE3 /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* Logger.swift */; }; E1F15FDA1E64B60A00391AE3 /* JSONHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = E11594981D01689F007F8B4F /* JSONHandler.swift */; }; E1F15FDB1E64B60A00391AE3 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1982BFE1D0AC2E2006B7330 /* Error.swift */; }; E1F15FDC1E64B60A00391AE3 /* AutomaticProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1D335CF1D3059A800E68E12 /* AutomaticProperties.swift */; }; @@ -100,7 +100,7 @@ /* Begin PBXFileReference section */ 1728208D2BA8BDE4002CD973 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; name = PrivacyInfo.xcprivacy; path = Sources/Mixpanel/PrivacyInfo.xcprivacy; sourceTree = SOURCE_ROOT; }; - 17C9D9072D4C170C008F04BB /* MPLogger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MPLogger.swift; sourceTree = ""; }; + 51DD56791D306B740045D3DB /* Logger.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Logger.swift; sourceTree = ""; }; 51DD56801D306B7B0045D3DB /* PrintLogging.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrintLogging.swift; sourceTree = ""; }; 51DD56811D306B7B0045D3DB /* FileLogging.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileLogging.swift; sourceTree = ""; }; 673ABE3921360CBE00B1784B /* Group.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Group.swift; sourceTree = ""; }; @@ -173,8 +173,8 @@ 51DD56771D306B620045D3DB /* Log */ = { isa = PBXGroup; children = ( - 17C9D9072D4C170C008F04BB /* MPLogger.swift */, 51DD56781D306B6B0045D3DB /* Logging */, + 51DD56791D306B740045D3DB /* Logger.swift */, ); name = Log; sourceTree = ""; @@ -479,7 +479,6 @@ 86F86EF7224554B900B69832 /* Group.swift in Sources */, 86F86ECA22443A4C00B69832 /* SessionMetadata.swift in Sources */, 86F86EC922443A4700B69832 /* Constants.swift in Sources */, - 17C9D90A2D4C170C008F04BB /* MPLogger.swift in Sources */, 86F86EC722443A3C00B69832 /* FileLogging.swift in Sources */, 86F86EC622443A3100B69832 /* Error.swift in Sources */, 86F86EC522443A2C00B69832 /* People.swift in Sources */, @@ -493,6 +492,7 @@ 86F86EBC224439F100B69832 /* PrintLogging.swift in Sources */, 868550AF2699096F001FCDDC /* MixpanelPersistence.swift in Sources */, 86F86EBB224439EB00B69832 /* FlushRequest.swift in Sources */, + 86F86EBA224439E300B69832 /* Logger.swift in Sources */, 86F86EB9224439DC00B69832 /* AutomaticProperties.swift in Sources */, 86F86F3722497F2900B69832 /* AutomaticEvents.swift in Sources */, 86F86EB7224439D300B69832 /* Mixpanel.swift in Sources */, @@ -514,8 +514,8 @@ 673ABE3A21360CBE00B1784B /* Group.swift in Sources */, E11594A11D01C597007F8B4F /* Track.swift in Sources */, E11594991D01689F007F8B4F /* JSONHandler.swift in Sources */, - 17C9D9092D4C170C008F04BB /* MPLogger.swift in Sources */, E1D335D01D3059A800E68E12 /* AutomaticProperties.swift in Sources */, + 51DD567C1D306B740045D3DB /* Logger.swift in Sources */, E165228F1D6781DF000D5949 /* MixpanelType.swift in Sources */, BB9614171F3BB87700C3EF3E /* ReadWriteLock.swift in Sources */, E190522D1F9FC1BC00900E5D /* SessionMetadata.swift in Sources */, @@ -535,7 +535,7 @@ 67FF65E521878416005161FA /* Group.swift in Sources */, E12782BB1D4AB5CB0025FB05 /* PrintLogging.swift in Sources */, E12782BC1D4AB5CB0025FB05 /* FileLogging.swift in Sources */, - 17C9D9082D4C170C008F04BB /* MPLogger.swift in Sources */, + E12782BD1D4AB5CB0025FB05 /* Logger.swift in Sources */, E12782BE1D4AB5CB0025FB05 /* Mixpanel.swift in Sources */, E12782BF1D4AB5CB0025FB05 /* MixpanelInstance.swift in Sources */, E12782C11D4AB5CB0025FB05 /* Network.swift in Sources */, @@ -563,8 +563,8 @@ 67FF65E421878414005161FA /* Group.swift in Sources */, E1F15FE01E64B60D00391AE3 /* MixpanelInstance.swift in Sources */, E1F15FDF1E64B60D00391AE3 /* Mixpanel.swift in Sources */, - 17C9D90B2D4C170C008F04BB /* MPLogger.swift in Sources */, E1F15FDC1E64B60A00391AE3 /* AutomaticProperties.swift in Sources */, + E1F15FD91E64B60600391AE3 /* Logger.swift in Sources */, E1F15FD61E64B5FC00391AE3 /* FlushRequest.swift in Sources */, E1F15FD71E64B60200391AE3 /* PrintLogging.swift in Sources */, 8625BEBD26D045CE0009BAA9 /* MPDB.swift in Sources */, diff --git a/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift b/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift index 3b2c86e9..62867bf4 100644 --- a/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift +++ b/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift @@ -15,63 +15,63 @@ class LoggerTests: XCTestCase { func testEnableDebug() { let counter = CounterLogging() - MPLogger.addLogging(counter) - MPLogger.enableLevel(.debug) + Logger.addLogging(counter) + Logger.enableLevel(.debug) - MPLogger.debug(message: "logged") + Logger.debug(message: "logged") XCTAssertEqual(1, counter.count) } func testEnableInfo() { let counter = CounterLogging() - MPLogger.addLogging(counter) - MPLogger.enableLevel(.info) - MPLogger.info(message: "logged") + Logger.addLogging(counter) + Logger.enableLevel(.info) + Logger.info(message: "logged") XCTAssertEqual(1, counter.count) } func testEnableWarning() { let counter = CounterLogging() - MPLogger.addLogging(counter) - MPLogger.enableLevel(.warning) - MPLogger.warn(message: "logged") + Logger.addLogging(counter) + Logger.enableLevel(.warning) + Logger.warn(message: "logged") XCTAssertEqual(1, counter.count) } func testEnableError() { let counter = CounterLogging() - MPLogger.addLogging(counter) - MPLogger.enableLevel(.error) - MPLogger.error(message: "logged") + Logger.addLogging(counter) + Logger.enableLevel(.error) + Logger.error(message: "logged") XCTAssertEqual(1, counter.count) } func testDisabledLogging() { let counter = CounterLogging() - MPLogger.addLogging(counter) - MPLogger.disableLevel(.debug) - MPLogger.debug(message: "not logged") + Logger.addLogging(counter) + Logger.disableLevel(.debug) + Logger.debug(message: "not logged") XCTAssertEqual(0, counter.count) - MPLogger.disableLevel(.error) - MPLogger.error(message: "not logged") + Logger.disableLevel(.error) + Logger.error(message: "not logged") XCTAssertEqual(0, counter.count) - MPLogger.disableLevel(.info) - MPLogger.info(message: "not logged") + Logger.disableLevel(.info) + Logger.info(message: "not logged") XCTAssertEqual(0, counter.count) - MPLogger.disableLevel(.warning) - MPLogger.warn(message: "not logged") + Logger.disableLevel(.warning) + Logger.warn(message: "not logged") XCTAssertEqual(0, counter.count) } } /// This is a stub that implements `Logging` to be passed to our `Logger` instance for testing -class CounterLogging: MPLogging { +class CounterLogging: Logging { var count = 0 - func addMessage(message: MPLogMessage) { + func addMessage(message: LogMessage) { count = count + 1 } } diff --git a/Sources/Error.swift b/Sources/Error.swift index 8046c44b..1a5d6f1b 100644 --- a/Sources/Error.swift +++ b/Sources/Error.swift @@ -36,7 +36,7 @@ class ErrorHandler { class func logError(_ error: Error) { let stackSymbols = Thread.callStackSymbols - MPLogger.error(message: "Error: \(error) \n Stack Symbols: \(stackSymbols)") + Logger.error(message: "Error: \(error) \n Stack Symbols: \(stackSymbols)") } } diff --git a/Sources/FileLogging.swift b/Sources/FileLogging.swift index 46e3d722..868a521d 100644 --- a/Sources/FileLogging.swift +++ b/Sources/FileLogging.swift @@ -9,7 +9,7 @@ import Foundation /// Logs all messages to a file -class FileLogging: MPLogging { +class FileLogging: Logging { private let fileHandle: FileHandle init(path: String) { @@ -28,7 +28,7 @@ class FileLogging: MPLogging { fileHandle.closeFile() } - func addMessage(message: MPLogMessage) { + func addMessage(message: LogMessage) { let string = "File: \(message.file) - Func: \(message.function) - " + "Level: \(message.level.rawValue) - Message: \(message.text)" if let data = string.data(using: String.Encoding.utf8) { diff --git a/Sources/Flush.swift b/Sources/Flush.swift index 10026095..a11618bb 100644 --- a/Sources/Flush.swift +++ b/Sources/Flush.swift @@ -122,8 +122,8 @@ class Flush: AppLifecycle { (entity["id"] as? Int32) ?? 0 } // Log data payload sent - MPLogger.debug(message: "Sending batch of data") - MPLogger.debug(message: batch as Any) + Logger.debug(message: "Sending batch of data") + Logger.debug(message: batch as Any) let requestData = JSONHandler.encodeAPIData(batch) if let requestData = requestData { #if os(iOS) diff --git a/Sources/FlushRequest.swift b/Sources/FlushRequest.swift index 7d8b1d5d..bf260364 100644 --- a/Sources/FlushRequest.swift +++ b/Sources/FlushRequest.swift @@ -65,13 +65,13 @@ class FlushRequest: Network { failure: { (reason, _, response) in self.networkConsecutiveFailures += 1 self.updateRetryDelay(response) - MPLogger.warn(message: "API request to \(resource.path) has failed with reason \(reason)") + Logger.warn(message: "API request to \(resource.path) has failed with reason \(reason)") completion(false) }, success: { (result, response) in self.networkConsecutiveFailures = 0 self.updateRetryDelay(response) if result == 0 { - MPLogger.info(message: "\(base) api rejected some items") + Logger.info(message: "\(base) api rejected some items") } completion(true) }) diff --git a/Sources/JSONHandler.swift b/Sources/JSONHandler.swift index 28dc5746..78b61fc6 100644 --- a/Sources/JSONHandler.swift +++ b/Sources/JSONHandler.swift @@ -16,7 +16,7 @@ class JSONHandler { let data: Data? = serializeJSONObject(obj) guard let d = data else { - MPLogger.warn(message: "couldn't serialize object") + Logger.warn(message: "couldn't serialize object") return nil } @@ -28,7 +28,7 @@ class JSONHandler { do { object = try JSONSerialization.jsonObject(with: data, options: []) } catch { - MPLogger.warn(message: "exception decoding object data") + Logger.warn(message: "exception decoding object data") } return object } @@ -44,7 +44,7 @@ class JSONHandler { } guard JSONSerialization.isValidJSONObject(serializableJSONObject) else { - MPLogger.warn(message: "object isn't valid and can't be serialzed to JSON") + Logger.warn(message: "object isn't valid and can't be serialzed to JSON") return nil } @@ -53,7 +53,7 @@ class JSONHandler { serializedObject = try JSONSerialization .data(withJSONObject: serializableJSONObject, options: []) } catch { - MPLogger.warn(message: "exception encoding api data") + Logger.warn(message: "exception encoding api data") } return serializedObject } @@ -110,7 +110,7 @@ class JSONHandler { // all nil properties outside of Arrays are converted to NSNull() return NSNull() } else { - MPLogger.info(message: "enforcing string on object") + Logger.info(message: "enforcing string on object") return objString } } diff --git a/Sources/MPLogger.swift b/Sources/Logger.swift similarity index 76% rename from Sources/MPLogger.swift rename to Sources/Logger.swift index 32cecfc1..3c974ad0 100644 --- a/Sources/MPLogger.swift +++ b/Sources/Logger.swift @@ -1,5 +1,5 @@ // -// MPLogger.swift +// Logger.swift // Logger // // Created by Sam Green on 7/8/16. @@ -10,7 +10,7 @@ import Foundation /// This defines the various levels of logging that a message may be tagged with. This allows hiding and /// showing different logging levels at run time depending on the environment -public enum MPLogLevel: String { +public enum LogLevel: String { /// Logging displays *all* logs and additional debug information that may be useful to a developer case debug @@ -26,7 +26,7 @@ public enum MPLogLevel: String { /// This holds all the data for each log message, since the formatting is up to each /// logging object. It is a simple bag of data -public struct MPLogMessage { +public struct LogMessage { /// The file where this log message was created public let file: String @@ -37,9 +37,9 @@ public struct MPLogMessage { public let text: String /// The level of the log message - public let level: MPLogLevel + public let level: LogLevel - init(path: String, function: String, text: String, level: MPLogLevel) { + init(path: String, function: String, text: String, level: LogLevel) { if let file = path.components(separatedBy: "/").last { self.file = file } else { @@ -52,31 +52,31 @@ public struct MPLogMessage { } /// Any object that conforms to this protocol may log messages -public protocol MPLogging { - func addMessage(message: MPLogMessage) +public protocol Logging { + func addMessage(message: LogMessage) } -public class MPLogger { - private static var loggers = [MPLogging]() - private static var enabledLevels = Set() - private static let readWriteLock: ReadWriteLock = ReadWriteLock(label: "mpLoggerLock") +public class Logger { + private static var loggers = [Logging]() + private static var enabledLevels = Set() + private static let readWriteLock: ReadWriteLock = ReadWriteLock(label: "loggerLock") /// Add a `Logging` object to receive all log messages - public class func addLogging(_ logging: MPLogging) { + public class func addLogging(_ logging: Logging) { readWriteLock.write { loggers.append(logging) } } /// Enable log messages of a specific `LogLevel` to be added to the log - class func enableLevel(_ level: MPLogLevel) { + class func enableLevel(_ level: LogLevel) { readWriteLock.write { enabledLevels.insert(level) } } /// Disable log messages of a specific `LogLevel` to prevent them from being logged - class func disableLevel(_ level: MPLogLevel) { + class func disableLevel(_ level: LogLevel) { readWriteLock.write { enabledLevels.remove(level) } @@ -85,55 +85,55 @@ public class MPLogger { /// debug: Adds a debug message to the Mixpanel log /// - Parameter message: The message to be added to the log class func debug(message: @autoclosure() -> Any, _ path: String = #file, _ function: String = #function) { - var enabledLevels = Set() + var enabledLevels = Set() readWriteLock.read { enabledLevels = self.enabledLevels } guard enabledLevels.contains(.debug) else { return } - forwardLogMessage(MPLogMessage(path: path, function: function, text: "\(message())", + forwardLogMessage(LogMessage(path: path, function: function, text: "\(message())", level: .debug)) } /// info: Adds an informational message to the Mixpanel log /// - Parameter message: The message to be added to the log class func info(message: @autoclosure() -> Any, _ path: String = #file, _ function: String = #function) { - var enabledLevels = Set() + var enabledLevels = Set() readWriteLock.read { enabledLevels = self.enabledLevels } guard enabledLevels.contains(.info) else { return } - forwardLogMessage(MPLogMessage(path: path, function: function, text: "\(message())", + forwardLogMessage(LogMessage(path: path, function: function, text: "\(message())", level: .info)) } /// warn: Adds a warning message to the Mixpanel log /// - Parameter message: The message to be added to the log class func warn(message: @autoclosure() -> Any, _ path: String = #file, _ function: String = #function) { - var enabledLevels = Set() + var enabledLevels = Set() readWriteLock.read { enabledLevels = self.enabledLevels } guard enabledLevels.contains(.warning) else { return } - forwardLogMessage(MPLogMessage(path: path, function: function, text: "\(message())", + forwardLogMessage(LogMessage(path: path, function: function, text: "\(message())", level: .warning)) } /// error: Adds an error message to the Mixpanel log /// - Parameter message: The message to be added to the log class func error(message: @autoclosure() -> Any, _ path: String = #file, _ function: String = #function) { - var enabledLevels = Set() + var enabledLevels = Set() readWriteLock.read { enabledLevels = self.enabledLevels } guard enabledLevels.contains(.error) else { return } - forwardLogMessage(MPLogMessage(path: path, function: function, text: "\(message())", + forwardLogMessage(LogMessage(path: path, function: function, text: "\(message())", level: .error)) } /// This forwards a `LogMessage` to each logger that has been added - class private func forwardLogMessage(_ message: MPLogMessage) { + class private func forwardLogMessage(_ message: LogMessage) { // Forward the log message to every registered Logging instance - var loggers = [MPLogging]() + var loggers = [Logging]() readWriteLock.read { loggers = self.loggers } diff --git a/Sources/MPDB.swift b/Sources/MPDB.swift index aea93578..e5ab9e65 100644 --- a/Sources/MPDB.swift +++ b/Sources/MPDB.swift @@ -45,13 +45,13 @@ class MPDB { } private func reconnect() { - MPLogger.warn(message: "No database connection found. Calling MPDB.open()") + Logger.warn(message: "No database connection found. Calling MPDB.open()") open() } func open() { if apiToken.isEmpty { - MPLogger.error(message: "Project token must not be empty. Database cannot be opened.") + Logger.error(message: "Project token must not be empty. Database cannot be opened.") return } if let dbPath = pathToDb() { @@ -59,14 +59,14 @@ class MPDB { logSqlError(message: "Error opening or creating database at path: \(dbPath)") close() } else { - MPLogger.info(message: "Successfully opened connection to database at path: \(dbPath)") + Logger.info(message: "Successfully opened connection to database at path: \(dbPath)") if let db = connection { let pragmaString = "PRAGMA journal_mode=WAL;" var pragmaStatement: OpaquePointer? if sqlite3_prepare_v2(db, pragmaString, -1, &pragmaStatement, nil) == SQLITE_OK { if sqlite3_step(pragmaStatement) == SQLITE_ROW { let res = String(cString: sqlite3_column_text(pragmaStatement, 0)) - MPLogger.info(message: "SQLite journal mode set to \(res)") + Logger.info(message: "SQLite journal mode set to \(res)") } else { logSqlError(message: "Failed to enable journal_mode=WAL") } @@ -85,7 +85,7 @@ class MPDB { func close() { sqlite3_close(connection) connection = nil - MPLogger.info(message: "Connection to database closed.") + Logger.info(message: "Connection to database closed.") } private func recreate() { @@ -95,10 +95,10 @@ class MPDB { let manager = FileManager.default if manager.fileExists(atPath: dbPath) { try manager.removeItem(atPath: dbPath) - MPLogger.info(message: "Deleted database file at path: \(dbPath)") + Logger.info(message: "Deleted database file at path: \(dbPath)") } } catch let error { - MPLogger.error(message: "Unable to remove database file at path: \(dbPath), error: \(error)") + Logger.error(message: "Unable to remove database file at path: \(dbPath), error: \(error)") } } reconnect() @@ -112,7 +112,7 @@ class MPDB { var createTableStatement: OpaquePointer? if sqlite3_prepare_v2(db, createTableString, -1, &createTableStatement, nil) == SQLITE_OK { if sqlite3_step(createTableStatement) == SQLITE_DONE { - MPLogger.info(message: "\(tableName) table created") + Logger.info(message: "\(tableName) table created") } else { logSqlError(message: "\(tableName) table create failed") } @@ -133,7 +133,7 @@ class MPDB { var createIndexStatement: OpaquePointer? if sqlite3_prepare_v2(db, createIndexString, -1, &createIndexStatement, nil) == SQLITE_OK { if sqlite3_step(createIndexStatement) == SQLITE_DONE { - MPLogger.info(message: "\(indexName) index created") + Logger.info(message: "\(indexName) index created") } else { logSqlError(message: "\(indexName) index creation failed") } @@ -167,7 +167,7 @@ class MPDB { sqlite3_bind_int(insertStatement, 2, flag ? 1 : 0) sqlite3_bind_double(insertStatement, 3, Date().timeIntervalSince1970) if sqlite3_step(insertStatement) == SQLITE_DONE { - MPLogger.info(message: "Successfully inserted row into table \(tableName)") + Logger.info(message: "Successfully inserted row into table \(tableName)") } else { logSqlError(message: "Failed to insert row into table \(tableName)") recreate() @@ -191,7 +191,7 @@ class MPDB { var deleteStatement: OpaquePointer? if sqlite3_prepare_v2(db, deleteString, -1, &deleteStatement, nil) == SQLITE_OK { if sqlite3_step(deleteStatement) == SQLITE_DONE { - MPLogger.info(message: "Successfully deleted rows from table \(tableName)") + Logger.info(message: "Successfully deleted rows from table \(tableName)") } else { logSqlError(message: "Failed to delete rows from table \(tableName)") recreate() @@ -223,7 +223,7 @@ class MPDB { var updateStatement: OpaquePointer? if sqlite3_prepare_v2(db, updateString, -1, &updateStatement, nil) == SQLITE_OK { if sqlite3_step(updateStatement) == SQLITE_DONE { - MPLogger.info(message: "Successfully updated rows from table \(tableName)") + Logger.info(message: "Successfully updated rows from table \(tableName)") } else { logSqlError(message: "Failed to update rows from table \(tableName)") recreate() @@ -266,7 +266,7 @@ class MPDB { } } if rowsRead > 0 { - MPLogger.info(message: "Successfully read \(rowsRead) from table \(tableName)") + Logger.info(message: "Successfully read \(rowsRead) from table \(tableName)") } } else { logSqlError(message: "SELECT statement for table \(tableName) could not be prepared") @@ -281,10 +281,10 @@ class MPDB { private func logSqlError(message: String? = nil) { if let db = connection { if let msg = message { - MPLogger.error(message: msg) + Logger.error(message: msg) } let sqlError = String(cString: sqlite3_errmsg(db)!) - MPLogger.error(message: sqlError) + Logger.error(message: sqlError) } else { reconnect() } diff --git a/Sources/Mixpanel.swift b/Sources/Mixpanel.swift index e5e3b674..0c5f4766 100644 --- a/Sources/Mixpanel.swift +++ b/Sources/Mixpanel.swift @@ -248,7 +248,7 @@ final class MixpanelManager { init() { instances = [String: MixpanelInstance]() - MPLogger.addLogging(PrintLogging()) + Logger.addLogging(PrintLogging()) readWriteLock = ReadWriteLock(label: "com.mixpanel.instance.manager.lock") instanceQueue = DispatchQueue(label: "com.mixpanel.instance.manager.instance", qos: .utility, autoreleaseFrequency: .workItem) } @@ -318,7 +318,7 @@ final class MixpanelManager { instance = instances[instanceName] } if instance == nil { - MPLogger.warn(message: "no such instance: \(instanceName)") + Logger.warn(message: "no such instance: \(instanceName)") return nil } return instance diff --git a/Sources/MixpanelInstance.swift b/Sources/MixpanelInstance.swift index cf3acf4f..bda85a8f 100644 --- a/Sources/MixpanelInstance.swift +++ b/Sources/MixpanelInstance.swift @@ -188,17 +188,17 @@ open class MixpanelInstance: CustomDebugStringConvertible, FlushDelegate, AEDele open var loggingEnabled: Bool = false { didSet { if loggingEnabled { - MPLogger.enableLevel(.debug) - MPLogger.enableLevel(.info) - MPLogger.enableLevel(.warning) - MPLogger.enableLevel(.error) - MPLogger.info(message: "Logging Enabled") + Logger.enableLevel(.debug) + Logger.enableLevel(.info) + Logger.enableLevel(.warning) + Logger.enableLevel(.error) + Logger.info(message: "Logging Enabled") } else { - MPLogger.info(message: "Logging Disabled") - MPLogger.disableLevel(.debug) - MPLogger.disableLevel(.info) - MPLogger.disableLevel(.warning) - MPLogger.disableLevel(.error) + Logger.info(message: "Logging Disabled") + Logger.disableLevel(.debug) + Logger.disableLevel(.info) + Logger.disableLevel(.warning) + Logger.disableLevel(.error) } #if DEBUG var trackProps: Properties = ["Logging Enabled": loggingEnabled] @@ -351,7 +351,7 @@ open class MixpanelInstance: CustomDebugStringConvertible, FlushDelegate, AEDele AutomaticProperties.automaticPropertiesLock.write { AutomaticProperties.properties["$wifi"] = wifi } - MPLogger.info(message: "reachability changed, wifi=\(wifi)") + Logger.info(message: "reachability changed, wifi=\(wifi)") } if SCNetworkReachabilitySetCallback(reachability, reachabilityCallback, &context) { if !SCNetworkReachabilitySetDispatchQueue(reachability, trackingQueue) { @@ -456,10 +456,10 @@ open class MixpanelInstance: CustomDebugStringConvertible, FlushDelegate, AEDele #if os(iOS) && !os(watchOS) && !targetEnvironment(macCatalyst) if let reachability = MixpanelInstance.reachability { if !SCNetworkReachabilitySetCallback(reachability, nil, nil) { - MPLogger.error(message: "\(self) error unsetting reachability callback") + Logger.error(message: "\(self) error unsetting reachability callback") } if !SCNetworkReachabilitySetDispatchQueue(reachability, nil) { - MPLogger.error(message: "\(self) error unsetting reachability dispatch queue") + Logger.error(message: "\(self) error unsetting reachability dispatch queue") } } #endif @@ -701,7 +701,7 @@ extension MixpanelInstance { return } if distinctId.isEmpty { - MPLogger.error(message: "\(self) cannot identify blank distinct id") + Logger.error(message: "\(self) cannot identify blank distinct id") if let completion = completion { DispatchQueue.main.async(execute: completion) } @@ -791,7 +791,7 @@ extension MixpanelInstance { } if distinctId.isEmpty { - MPLogger.error(message: "\(self) cannot identify blank distinct id") + Logger.error(message: "\(self) cannot identify blank distinct id") if let completion = completion { DispatchQueue.main.async(execute: completion) } @@ -799,7 +799,7 @@ extension MixpanelInstance { } if alias.isEmpty { - MPLogger.error(message: "\(self) create alias called with empty alias") + Logger.error(message: "\(self) create alias called with empty alias") if let completion = completion { DispatchQueue.main.async(execute: completion) } @@ -850,7 +850,7 @@ extension MixpanelInstance { } flush(completion: completion) } else { - MPLogger.error(message: "alias: \(alias) matches distinctId: \(distinctId) - skipping api call.") + Logger.error(message: "alias: \(alias) matches distinctId: \(distinctId) - skipping api call.") if let completion = completion { DispatchQueue.main.async(execute: completion) } @@ -1159,7 +1159,7 @@ extension MixpanelInstance { if !(group.groupKey == groupKey && group.groupID.equals(rhs: groupID)) { // we somehow hit a collision on the map key, return a new group with the correct key and ID - MPLogger.info(message: "groups dictionary key collision: \(key)") + Logger.info(message: "groups dictionary key collision: \(key)") let newGroup = Group(apiToken: apiToken, serialQueue: trackingQueue, lock: self.readWriteLock, diff --git a/Sources/MixpanelPersistence.swift b/Sources/MixpanelPersistence.swift index 61a081a2..c6a6a1b0 100644 --- a/Sources/MixpanelPersistence.swift +++ b/Sources/MixpanelPersistence.swift @@ -139,7 +139,7 @@ class MixpanelPersistence { defaults.set(timedEventsData, forKey: "\(prefix)\(MixpanelUserDefaultsKeys.timedEvents)") defaults.synchronize() } catch { - MPLogger.warn(message: "Failed to archive timed events") + Logger.warn(message: "Failed to archive timed events") } } @@ -154,7 +154,7 @@ class MixpanelPersistence { do { return try NSKeyedUnarchiver.unarchivedObject(ofClasses: archivedClasses, from: timedEventsData) as? InternalProperties ?? InternalProperties() } catch { - MPLogger.warn(message: "Failed to unarchive timed events") + Logger.warn(message: "Failed to unarchive timed events") return InternalProperties() } } @@ -169,7 +169,7 @@ class MixpanelPersistence { defaults.set(superPropertiesData, forKey: "\(prefix)\(MixpanelUserDefaultsKeys.superProperties)") defaults.synchronize() } catch { - MPLogger.warn(message: "Failed to archive super properties") + Logger.warn(message: "Failed to archive super properties") } } @@ -184,7 +184,7 @@ class MixpanelPersistence { do { return try NSKeyedUnarchiver.unarchivedObject(ofClasses: archivedClasses, from: superPropertiesData) as? InternalProperties ?? InternalProperties() } catch { - MPLogger.warn(message: "Failed to unarchive super properties") + Logger.warn(message: "Failed to unarchive super properties") return InternalProperties() } } @@ -355,14 +355,14 @@ class MixpanelPersistence { if #available(iOS 11.0, macOS 10.13, watchOS 4.0, tvOS 11.0, *) { guard let data = try? Data(contentsOf: URL(fileURLWithPath: filePath)), let unarchivedData = try? NSKeyedUnarchiver.unarchivedObject(ofClasses: MixpanelPersistence.archivedClasses, from: data) else { - MPLogger.info(message: "Unable to read file at path: \(filePath)") + Logger.info(message: "Unable to read file at path: \(filePath)") removeArchivedFile(atPath: filePath) return nil } return unarchivedData } else { guard let unarchivedData = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) else { - MPLogger.info(message: "Unable to read file at path: \(filePath)") + Logger.info(message: "Unable to read file at path: \(filePath)") removeArchivedFile(atPath: filePath) return nil } @@ -374,7 +374,7 @@ class MixpanelPersistence { do { try FileManager.default.removeItem(atPath: filePath) } catch let err { - MPLogger.info(message: "Unable to remove file at path: \(filePath), error: \(err)") + Logger.info(message: "Unable to remove file at path: \(filePath), error: \(err)") } } @@ -440,12 +440,12 @@ class MixpanelPersistence { private func unarchiveWithType(_ type: String) -> Any? { let filePath = filePathWithType(type) guard let path = filePath else { - MPLogger.info(message: "bad file path, cant fetch file") + Logger.info(message: "bad file path, cant fetch file") return nil } guard let unarchivedData = unarchiveWithFilePath(path) else { - MPLogger.info(message: "can't unarchive file") + Logger.info(message: "can't unarchive file") return nil } diff --git a/Sources/Network.swift b/Sources/Network.swift index 3d5fba0f..f4620144 100644 --- a/Sources/Network.swift +++ b/Sources/Network.swift @@ -107,8 +107,8 @@ class Network { return nil } - MPLogger.debug(message: "Fetching URL") - MPLogger.debug(message: url.absoluteURL) + Logger.debug(message: "Fetching URL") + Logger.debug(message: url.absoluteURL) var request = URLRequest(url: url) request.httpMethod = resource.method.rawValue request.httpBody = resource.requestBody diff --git a/Sources/PrintLogging.swift b/Sources/PrintLogging.swift index 732c27d5..b1c8d4a9 100644 --- a/Sources/PrintLogging.swift +++ b/Sources/PrintLogging.swift @@ -9,16 +9,16 @@ import Foundation /// Simply formats and prints the object by calling `print` -class PrintLogging: MPLogging { - func addMessage(message: MPLogMessage) { +class PrintLogging: Logging { + func addMessage(message: LogMessage) { print("[Mixpanel - \(message.file) - func \(message.function)] (\(message.level.rawValue)) - \(message.text)") } } /// Simply formats and prints the object by calling `debugPrint`, this makes things a bit easier if you /// need to print data that may be quoted for instance. -class PrintDebugLogging: MPLogging { - func addMessage(message: MPLogMessage) { +class PrintDebugLogging: Logging { + func addMessage(message: LogMessage) { debugPrint("[Mixpanel - \(message.file) - func \(message.function)] (\(message.level.rawValue)) - \(message.text)") } } diff --git a/Sources/Track.swift b/Sources/Track.swift index eeb445eb..ffc64143 100644 --- a/Sources/Track.swift +++ b/Sources/Track.swift @@ -41,7 +41,7 @@ class Track { if let event = event { ev = event } else { - MPLogger.info(message: "mixpanel track called with empty event parameter. using 'mp_event'") + Logger.info(message: "mixpanel track called with empty event parameter. using 'mp_event'") } if !(mixpanelInstance?.trackAutomaticEventsEnabled ?? false) && ev.hasPrefix("$ae_") { return timedEvents @@ -140,7 +140,7 @@ class Track { } var updatedTimedEvents = timedEvents guard let event = event, !event.isEmpty else { - MPLogger.error(message: "mixpanel cannot time an empty event") + Logger.error(message: "mixpanel cannot time an empty event") return updatedTimedEvents } updatedTimedEvents[event] = startTime @@ -156,7 +156,7 @@ class Track { func clearTimedEvent(event: String?, timedEvents: InternalProperties) -> InternalProperties { var updatedTimedEvents = timedEvents guard let event = event, !event.isEmpty else { - MPLogger.error(message: "mixpanel cannot clear an empty timed event") + Logger.error(message: "mixpanel cannot clear an empty timed event") return updatedTimedEvents } updatedTimedEvents.removeValue(forKey: event) From af5f9753aeb6c30d44f8e3a649fa95364b40d9b3 Mon Sep 17 00:00:00 2001 From: Jared McFarland Date: Thu, 30 Jan 2025 12:44:04 -0800 Subject: [PATCH 5/8] add Mixpanel prefix to avoid namespace clashes --- Mixpanel.xcodeproj/project.pbxproj | 20 ++++---- Sources/Error.swift | 2 +- Sources/FileLogging.swift | 4 +- Sources/Flush.swift | 4 +- Sources/FlushRequest.swift | 4 +- Sources/JSONHandler.swift | 10 ++-- Sources/MPDB.swift | 30 ++++++------ Sources/Mixpanel.swift | 4 +- Sources/MixpanelInstance.swift | 36 +++++++------- .../{Logger.swift => MixpanelLogger.swift} | 48 +++++++++---------- Sources/MixpanelPersistence.swift | 18 +++---- Sources/Network.swift | 4 +- Sources/PrintLogging.swift | 8 ++-- Sources/Track.swift | 6 +-- 14 files changed, 99 insertions(+), 99 deletions(-) rename Sources/{Logger.swift => MixpanelLogger.swift} (74%) diff --git a/Mixpanel.xcodeproj/project.pbxproj b/Mixpanel.xcodeproj/project.pbxproj index 17a24ac8..e8aa981b 100644 --- a/Mixpanel.xcodeproj/project.pbxproj +++ b/Mixpanel.xcodeproj/project.pbxproj @@ -11,7 +11,7 @@ 17C6547B2BB1F16000C8A126 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 1728208D2BA8BDE4002CD973 /* PrivacyInfo.xcprivacy */; }; 17C6547C2BB1F16400C8A126 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 1728208D2BA8BDE4002CD973 /* PrivacyInfo.xcprivacy */; }; 17C6547D2BB1F16800C8A126 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 1728208D2BA8BDE4002CD973 /* PrivacyInfo.xcprivacy */; }; - 51DD567C1D306B740045D3DB /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* Logger.swift */; }; + 51DD567C1D306B740045D3DB /* MixpanelLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* MixpanelLogger.swift */; }; 51DD56831D306B7B0045D3DB /* PrintLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56801D306B7B0045D3DB /* PrintLogging.swift */; }; 51DD56841D306B7B0045D3DB /* FileLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56811D306B7B0045D3DB /* FileLogging.swift */; }; 673ABE3A21360CBE00B1784B /* Group.swift in Sources */ = {isa = PBXBuildFile; fileRef = 673ABE3921360CBE00B1784B /* Group.swift */; }; @@ -28,7 +28,7 @@ 86F86EB7224439D300B69832 /* Mixpanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = E115948A1CFF1538007F8B4F /* Mixpanel.swift */; }; 86F86EB8224439D300B69832 /* MixpanelInstance.swift in Sources */ = {isa = PBXBuildFile; fileRef = E115948D1D000709007F8B4F /* MixpanelInstance.swift */; }; 86F86EB9224439DC00B69832 /* AutomaticProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1D335CF1D3059A800E68E12 /* AutomaticProperties.swift */; }; - 86F86EBA224439E300B69832 /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* Logger.swift */; }; + 86F86EBA224439E300B69832 /* MixpanelLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* MixpanelLogger.swift */; }; 86F86EBB224439EB00B69832 /* FlushRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1D335CB1D303A0D00E68E12 /* FlushRequest.swift */; }; 86F86EBC224439F100B69832 /* PrintLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56801D306B7B0045D3DB /* PrintLogging.swift */; }; 86F86EBD224439F500B69832 /* Flush.swift in Sources */ = {isa = PBXBuildFile; fileRef = E115949E1D01BE14007F8B4F /* Flush.swift */; }; @@ -55,7 +55,7 @@ E11594A11D01C597007F8B4F /* Track.swift in Sources */ = {isa = PBXBuildFile; fileRef = E11594A01D01C597007F8B4F /* Track.swift */; }; E12782BB1D4AB5CB0025FB05 /* PrintLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56801D306B7B0045D3DB /* PrintLogging.swift */; }; E12782BC1D4AB5CB0025FB05 /* FileLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56811D306B7B0045D3DB /* FileLogging.swift */; }; - E12782BD1D4AB5CB0025FB05 /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* Logger.swift */; }; + E12782BD1D4AB5CB0025FB05 /* MixpanelLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* MixpanelLogger.swift */; }; E12782BE1D4AB5CB0025FB05 /* Mixpanel.swift in Sources */ = {isa = PBXBuildFile; fileRef = E115948A1CFF1538007F8B4F /* Mixpanel.swift */; }; E12782BF1D4AB5CB0025FB05 /* MixpanelInstance.swift in Sources */ = {isa = PBXBuildFile; fileRef = E115948D1D000709007F8B4F /* MixpanelInstance.swift */; }; E12782C11D4AB5CB0025FB05 /* Network.swift in Sources */ = {isa = PBXBuildFile; fileRef = E11594961D006022007F8B4F /* Network.swift */; }; @@ -85,7 +85,7 @@ E1F15FD61E64B5FC00391AE3 /* FlushRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1D335CB1D303A0D00E68E12 /* FlushRequest.swift */; }; E1F15FD71E64B60200391AE3 /* PrintLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56801D306B7B0045D3DB /* PrintLogging.swift */; }; E1F15FD81E64B60200391AE3 /* FileLogging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56811D306B7B0045D3DB /* FileLogging.swift */; }; - E1F15FD91E64B60600391AE3 /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* Logger.swift */; }; + E1F15FD91E64B60600391AE3 /* MixpanelLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 51DD56791D306B740045D3DB /* MixpanelLogger.swift */; }; E1F15FDA1E64B60A00391AE3 /* JSONHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = E11594981D01689F007F8B4F /* JSONHandler.swift */; }; E1F15FDB1E64B60A00391AE3 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1982BFE1D0AC2E2006B7330 /* Error.swift */; }; E1F15FDC1E64B60A00391AE3 /* AutomaticProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1D335CF1D3059A800E68E12 /* AutomaticProperties.swift */; }; @@ -100,7 +100,7 @@ /* Begin PBXFileReference section */ 1728208D2BA8BDE4002CD973 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; name = PrivacyInfo.xcprivacy; path = Sources/Mixpanel/PrivacyInfo.xcprivacy; sourceTree = SOURCE_ROOT; }; - 51DD56791D306B740045D3DB /* Logger.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Logger.swift; sourceTree = ""; }; + 51DD56791D306B740045D3DB /* MixpanelLogger.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MixpanelLogger.swift; sourceTree = ""; }; 51DD56801D306B7B0045D3DB /* PrintLogging.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrintLogging.swift; sourceTree = ""; }; 51DD56811D306B7B0045D3DB /* FileLogging.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FileLogging.swift; sourceTree = ""; }; 673ABE3921360CBE00B1784B /* Group.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Group.swift; sourceTree = ""; }; @@ -174,7 +174,7 @@ isa = PBXGroup; children = ( 51DD56781D306B6B0045D3DB /* Logging */, - 51DD56791D306B740045D3DB /* Logger.swift */, + 51DD56791D306B740045D3DB /* MixpanelLogger.swift */, ); name = Log; sourceTree = ""; @@ -492,7 +492,7 @@ 86F86EBC224439F100B69832 /* PrintLogging.swift in Sources */, 868550AF2699096F001FCDDC /* MixpanelPersistence.swift in Sources */, 86F86EBB224439EB00B69832 /* FlushRequest.swift in Sources */, - 86F86EBA224439E300B69832 /* Logger.swift in Sources */, + 86F86EBA224439E300B69832 /* MixpanelLogger.swift in Sources */, 86F86EB9224439DC00B69832 /* AutomaticProperties.swift in Sources */, 86F86F3722497F2900B69832 /* AutomaticEvents.swift in Sources */, 86F86EB7224439D300B69832 /* Mixpanel.swift in Sources */, @@ -515,7 +515,7 @@ E11594A11D01C597007F8B4F /* Track.swift in Sources */, E11594991D01689F007F8B4F /* JSONHandler.swift in Sources */, E1D335D01D3059A800E68E12 /* AutomaticProperties.swift in Sources */, - 51DD567C1D306B740045D3DB /* Logger.swift in Sources */, + 51DD567C1D306B740045D3DB /* MixpanelLogger.swift in Sources */, E165228F1D6781DF000D5949 /* MixpanelType.swift in Sources */, BB9614171F3BB87700C3EF3E /* ReadWriteLock.swift in Sources */, E190522D1F9FC1BC00900E5D /* SessionMetadata.swift in Sources */, @@ -535,7 +535,7 @@ 67FF65E521878416005161FA /* Group.swift in Sources */, E12782BB1D4AB5CB0025FB05 /* PrintLogging.swift in Sources */, E12782BC1D4AB5CB0025FB05 /* FileLogging.swift in Sources */, - E12782BD1D4AB5CB0025FB05 /* Logger.swift in Sources */, + E12782BD1D4AB5CB0025FB05 /* MixpanelLogger.swift in Sources */, E12782BE1D4AB5CB0025FB05 /* Mixpanel.swift in Sources */, E12782BF1D4AB5CB0025FB05 /* MixpanelInstance.swift in Sources */, E12782C11D4AB5CB0025FB05 /* Network.swift in Sources */, @@ -564,7 +564,7 @@ E1F15FE01E64B60D00391AE3 /* MixpanelInstance.swift in Sources */, E1F15FDF1E64B60D00391AE3 /* Mixpanel.swift in Sources */, E1F15FDC1E64B60A00391AE3 /* AutomaticProperties.swift in Sources */, - E1F15FD91E64B60600391AE3 /* Logger.swift in Sources */, + E1F15FD91E64B60600391AE3 /* MixpanelLogger.swift in Sources */, E1F15FD61E64B5FC00391AE3 /* FlushRequest.swift in Sources */, E1F15FD71E64B60200391AE3 /* PrintLogging.swift in Sources */, 8625BEBD26D045CE0009BAA9 /* MPDB.swift in Sources */, diff --git a/Sources/Error.swift b/Sources/Error.swift index 1a5d6f1b..9708995b 100644 --- a/Sources/Error.swift +++ b/Sources/Error.swift @@ -36,7 +36,7 @@ class ErrorHandler { class func logError(_ error: Error) { let stackSymbols = Thread.callStackSymbols - Logger.error(message: "Error: \(error) \n Stack Symbols: \(stackSymbols)") + MixpanelLogger.error(message: "Error: \(error) \n Stack Symbols: \(stackSymbols)") } } diff --git a/Sources/FileLogging.swift b/Sources/FileLogging.swift index 868a521d..017c4af2 100644 --- a/Sources/FileLogging.swift +++ b/Sources/FileLogging.swift @@ -9,7 +9,7 @@ import Foundation /// Logs all messages to a file -class FileLogging: Logging { +class FileLogging: MixpanelLogging { private let fileHandle: FileHandle init(path: String) { @@ -28,7 +28,7 @@ class FileLogging: Logging { fileHandle.closeFile() } - func addMessage(message: LogMessage) { + func addMessage(message: MixpanelLogMessage) { let string = "File: \(message.file) - Func: \(message.function) - " + "Level: \(message.level.rawValue) - Message: \(message.text)" if let data = string.data(using: String.Encoding.utf8) { diff --git a/Sources/Flush.swift b/Sources/Flush.swift index a11618bb..91ff932e 100644 --- a/Sources/Flush.swift +++ b/Sources/Flush.swift @@ -122,8 +122,8 @@ class Flush: AppLifecycle { (entity["id"] as? Int32) ?? 0 } // Log data payload sent - Logger.debug(message: "Sending batch of data") - Logger.debug(message: batch as Any) + MixpanelLogger.debug(message: "Sending batch of data") + MixpanelLogger.debug(message: batch as Any) let requestData = JSONHandler.encodeAPIData(batch) if let requestData = requestData { #if os(iOS) diff --git a/Sources/FlushRequest.swift b/Sources/FlushRequest.swift index bf260364..c51e1653 100644 --- a/Sources/FlushRequest.swift +++ b/Sources/FlushRequest.swift @@ -65,13 +65,13 @@ class FlushRequest: Network { failure: { (reason, _, response) in self.networkConsecutiveFailures += 1 self.updateRetryDelay(response) - Logger.warn(message: "API request to \(resource.path) has failed with reason \(reason)") + MixpanelLogger.warn(message: "API request to \(resource.path) has failed with reason \(reason)") completion(false) }, success: { (result, response) in self.networkConsecutiveFailures = 0 self.updateRetryDelay(response) if result == 0 { - Logger.info(message: "\(base) api rejected some items") + MixpanelLogger.info(message: "\(base) api rejected some items") } completion(true) }) diff --git a/Sources/JSONHandler.swift b/Sources/JSONHandler.swift index 78b61fc6..9fee4c2e 100644 --- a/Sources/JSONHandler.swift +++ b/Sources/JSONHandler.swift @@ -16,7 +16,7 @@ class JSONHandler { let data: Data? = serializeJSONObject(obj) guard let d = data else { - Logger.warn(message: "couldn't serialize object") + MixpanelLogger.warn(message: "couldn't serialize object") return nil } @@ -28,7 +28,7 @@ class JSONHandler { do { object = try JSONSerialization.jsonObject(with: data, options: []) } catch { - Logger.warn(message: "exception decoding object data") + MixpanelLogger.warn(message: "exception decoding object data") } return object } @@ -44,7 +44,7 @@ class JSONHandler { } guard JSONSerialization.isValidJSONObject(serializableJSONObject) else { - Logger.warn(message: "object isn't valid and can't be serialzed to JSON") + MixpanelLogger.warn(message: "object isn't valid and can't be serialzed to JSON") return nil } @@ -53,7 +53,7 @@ class JSONHandler { serializedObject = try JSONSerialization .data(withJSONObject: serializableJSONObject, options: []) } catch { - Logger.warn(message: "exception encoding api data") + MixpanelLogger.warn(message: "exception encoding api data") } return serializedObject } @@ -110,7 +110,7 @@ class JSONHandler { // all nil properties outside of Arrays are converted to NSNull() return NSNull() } else { - Logger.info(message: "enforcing string on object") + MixpanelLogger.info(message: "enforcing string on object") return objString } } diff --git a/Sources/MPDB.swift b/Sources/MPDB.swift index e5ab9e65..4424b566 100644 --- a/Sources/MPDB.swift +++ b/Sources/MPDB.swift @@ -45,13 +45,13 @@ class MPDB { } private func reconnect() { - Logger.warn(message: "No database connection found. Calling MPDB.open()") + MixpanelLogger.warn(message: "No database connection found. Calling MPDB.open()") open() } func open() { if apiToken.isEmpty { - Logger.error(message: "Project token must not be empty. Database cannot be opened.") + MixpanelLogger.error(message: "Project token must not be empty. Database cannot be opened.") return } if let dbPath = pathToDb() { @@ -59,14 +59,14 @@ class MPDB { logSqlError(message: "Error opening or creating database at path: \(dbPath)") close() } else { - Logger.info(message: "Successfully opened connection to database at path: \(dbPath)") + MixpanelLogger.info(message: "Successfully opened connection to database at path: \(dbPath)") if let db = connection { let pragmaString = "PRAGMA journal_mode=WAL;" var pragmaStatement: OpaquePointer? if sqlite3_prepare_v2(db, pragmaString, -1, &pragmaStatement, nil) == SQLITE_OK { if sqlite3_step(pragmaStatement) == SQLITE_ROW { let res = String(cString: sqlite3_column_text(pragmaStatement, 0)) - Logger.info(message: "SQLite journal mode set to \(res)") + MixpanelLogger.info(message: "SQLite journal mode set to \(res)") } else { logSqlError(message: "Failed to enable journal_mode=WAL") } @@ -85,7 +85,7 @@ class MPDB { func close() { sqlite3_close(connection) connection = nil - Logger.info(message: "Connection to database closed.") + MixpanelLogger.info(message: "Connection to database closed.") } private func recreate() { @@ -95,10 +95,10 @@ class MPDB { let manager = FileManager.default if manager.fileExists(atPath: dbPath) { try manager.removeItem(atPath: dbPath) - Logger.info(message: "Deleted database file at path: \(dbPath)") + MixpanelLogger.info(message: "Deleted database file at path: \(dbPath)") } } catch let error { - Logger.error(message: "Unable to remove database file at path: \(dbPath), error: \(error)") + MixpanelLogger.error(message: "Unable to remove database file at path: \(dbPath), error: \(error)") } } reconnect() @@ -112,7 +112,7 @@ class MPDB { var createTableStatement: OpaquePointer? if sqlite3_prepare_v2(db, createTableString, -1, &createTableStatement, nil) == SQLITE_OK { if sqlite3_step(createTableStatement) == SQLITE_DONE { - Logger.info(message: "\(tableName) table created") + MixpanelLogger.info(message: "\(tableName) table created") } else { logSqlError(message: "\(tableName) table create failed") } @@ -133,7 +133,7 @@ class MPDB { var createIndexStatement: OpaquePointer? if sqlite3_prepare_v2(db, createIndexString, -1, &createIndexStatement, nil) == SQLITE_OK { if sqlite3_step(createIndexStatement) == SQLITE_DONE { - Logger.info(message: "\(indexName) index created") + MixpanelLogger.info(message: "\(indexName) index created") } else { logSqlError(message: "\(indexName) index creation failed") } @@ -167,7 +167,7 @@ class MPDB { sqlite3_bind_int(insertStatement, 2, flag ? 1 : 0) sqlite3_bind_double(insertStatement, 3, Date().timeIntervalSince1970) if sqlite3_step(insertStatement) == SQLITE_DONE { - Logger.info(message: "Successfully inserted row into table \(tableName)") + MixpanelLogger.info(message: "Successfully inserted row into table \(tableName)") } else { logSqlError(message: "Failed to insert row into table \(tableName)") recreate() @@ -191,7 +191,7 @@ class MPDB { var deleteStatement: OpaquePointer? if sqlite3_prepare_v2(db, deleteString, -1, &deleteStatement, nil) == SQLITE_OK { if sqlite3_step(deleteStatement) == SQLITE_DONE { - Logger.info(message: "Successfully deleted rows from table \(tableName)") + MixpanelLogger.info(message: "Successfully deleted rows from table \(tableName)") } else { logSqlError(message: "Failed to delete rows from table \(tableName)") recreate() @@ -223,7 +223,7 @@ class MPDB { var updateStatement: OpaquePointer? if sqlite3_prepare_v2(db, updateString, -1, &updateStatement, nil) == SQLITE_OK { if sqlite3_step(updateStatement) == SQLITE_DONE { - Logger.info(message: "Successfully updated rows from table \(tableName)") + MixpanelLogger.info(message: "Successfully updated rows from table \(tableName)") } else { logSqlError(message: "Failed to update rows from table \(tableName)") recreate() @@ -266,7 +266,7 @@ class MPDB { } } if rowsRead > 0 { - Logger.info(message: "Successfully read \(rowsRead) from table \(tableName)") + MixpanelLogger.info(message: "Successfully read \(rowsRead) from table \(tableName)") } } else { logSqlError(message: "SELECT statement for table \(tableName) could not be prepared") @@ -281,10 +281,10 @@ class MPDB { private func logSqlError(message: String? = nil) { if let db = connection { if let msg = message { - Logger.error(message: msg) + MixpanelLogger.error(message: msg) } let sqlError = String(cString: sqlite3_errmsg(db)!) - Logger.error(message: sqlError) + MixpanelLogger.error(message: sqlError) } else { reconnect() } diff --git a/Sources/Mixpanel.swift b/Sources/Mixpanel.swift index 0c5f4766..977508c6 100644 --- a/Sources/Mixpanel.swift +++ b/Sources/Mixpanel.swift @@ -248,7 +248,7 @@ final class MixpanelManager { init() { instances = [String: MixpanelInstance]() - Logger.addLogging(PrintLogging()) + MixpanelLogger.addLogging(PrintLogging()) readWriteLock = ReadWriteLock(label: "com.mixpanel.instance.manager.lock") instanceQueue = DispatchQueue(label: "com.mixpanel.instance.manager.instance", qos: .utility, autoreleaseFrequency: .workItem) } @@ -318,7 +318,7 @@ final class MixpanelManager { instance = instances[instanceName] } if instance == nil { - Logger.warn(message: "no such instance: \(instanceName)") + MixpanelLogger.warn(message: "no such instance: \(instanceName)") return nil } return instance diff --git a/Sources/MixpanelInstance.swift b/Sources/MixpanelInstance.swift index bda85a8f..77131e32 100644 --- a/Sources/MixpanelInstance.swift +++ b/Sources/MixpanelInstance.swift @@ -188,17 +188,17 @@ open class MixpanelInstance: CustomDebugStringConvertible, FlushDelegate, AEDele open var loggingEnabled: Bool = false { didSet { if loggingEnabled { - Logger.enableLevel(.debug) - Logger.enableLevel(.info) - Logger.enableLevel(.warning) - Logger.enableLevel(.error) - Logger.info(message: "Logging Enabled") + MixpanelLogger.enableLevel(.debug) + MixpanelLogger.enableLevel(.info) + MixpanelLogger.enableLevel(.warning) + MixpanelLogger.enableLevel(.error) + MixpanelLogger.info(message: "Logging Enabled") } else { - Logger.info(message: "Logging Disabled") - Logger.disableLevel(.debug) - Logger.disableLevel(.info) - Logger.disableLevel(.warning) - Logger.disableLevel(.error) + MixpanelLogger.info(message: "Logging Disabled") + MixpanelLogger.disableLevel(.debug) + MixpanelLogger.disableLevel(.info) + MixpanelLogger.disableLevel(.warning) + MixpanelLogger.disableLevel(.error) } #if DEBUG var trackProps: Properties = ["Logging Enabled": loggingEnabled] @@ -351,7 +351,7 @@ open class MixpanelInstance: CustomDebugStringConvertible, FlushDelegate, AEDele AutomaticProperties.automaticPropertiesLock.write { AutomaticProperties.properties["$wifi"] = wifi } - Logger.info(message: "reachability changed, wifi=\(wifi)") + MixpanelLogger.info(message: "reachability changed, wifi=\(wifi)") } if SCNetworkReachabilitySetCallback(reachability, reachabilityCallback, &context) { if !SCNetworkReachabilitySetDispatchQueue(reachability, trackingQueue) { @@ -456,10 +456,10 @@ open class MixpanelInstance: CustomDebugStringConvertible, FlushDelegate, AEDele #if os(iOS) && !os(watchOS) && !targetEnvironment(macCatalyst) if let reachability = MixpanelInstance.reachability { if !SCNetworkReachabilitySetCallback(reachability, nil, nil) { - Logger.error(message: "\(self) error unsetting reachability callback") + MixpanelLogger.error(message: "\(self) error unsetting reachability callback") } if !SCNetworkReachabilitySetDispatchQueue(reachability, nil) { - Logger.error(message: "\(self) error unsetting reachability dispatch queue") + MixpanelLogger.error(message: "\(self) error unsetting reachability dispatch queue") } } #endif @@ -701,7 +701,7 @@ extension MixpanelInstance { return } if distinctId.isEmpty { - Logger.error(message: "\(self) cannot identify blank distinct id") + MixpanelLogger.error(message: "\(self) cannot identify blank distinct id") if let completion = completion { DispatchQueue.main.async(execute: completion) } @@ -791,7 +791,7 @@ extension MixpanelInstance { } if distinctId.isEmpty { - Logger.error(message: "\(self) cannot identify blank distinct id") + MixpanelLogger.error(message: "\(self) cannot identify blank distinct id") if let completion = completion { DispatchQueue.main.async(execute: completion) } @@ -799,7 +799,7 @@ extension MixpanelInstance { } if alias.isEmpty { - Logger.error(message: "\(self) create alias called with empty alias") + MixpanelLogger.error(message: "\(self) create alias called with empty alias") if let completion = completion { DispatchQueue.main.async(execute: completion) } @@ -850,7 +850,7 @@ extension MixpanelInstance { } flush(completion: completion) } else { - Logger.error(message: "alias: \(alias) matches distinctId: \(distinctId) - skipping api call.") + MixpanelLogger.error(message: "alias: \(alias) matches distinctId: \(distinctId) - skipping api call.") if let completion = completion { DispatchQueue.main.async(execute: completion) } @@ -1159,7 +1159,7 @@ extension MixpanelInstance { if !(group.groupKey == groupKey && group.groupID.equals(rhs: groupID)) { // we somehow hit a collision on the map key, return a new group with the correct key and ID - Logger.info(message: "groups dictionary key collision: \(key)") + MixpanelLogger.info(message: "groups dictionary key collision: \(key)") let newGroup = Group(apiToken: apiToken, serialQueue: trackingQueue, lock: self.readWriteLock, diff --git a/Sources/Logger.swift b/Sources/MixpanelLogger.swift similarity index 74% rename from Sources/Logger.swift rename to Sources/MixpanelLogger.swift index 3c974ad0..6e1be7ef 100644 --- a/Sources/Logger.swift +++ b/Sources/MixpanelLogger.swift @@ -1,6 +1,6 @@ // -// Logger.swift -// Logger +// MixpanelLogger.swift +// MixpanelLogger // // Created by Sam Green on 7/8/16. // Copyright © 2016 Mixpanel. All rights reserved. @@ -10,7 +10,7 @@ import Foundation /// This defines the various levels of logging that a message may be tagged with. This allows hiding and /// showing different logging levels at run time depending on the environment -public enum LogLevel: String { +public enum MixpanelLogLevel: String { /// Logging displays *all* logs and additional debug information that may be useful to a developer case debug @@ -26,7 +26,7 @@ public enum LogLevel: String { /// This holds all the data for each log message, since the formatting is up to each /// logging object. It is a simple bag of data -public struct LogMessage { +public struct MixpanelLogMessage { /// The file where this log message was created public let file: String @@ -37,9 +37,9 @@ public struct LogMessage { public let text: String /// The level of the log message - public let level: LogLevel + public let level: MixpanelLogLevel - init(path: String, function: String, text: String, level: LogLevel) { + init(path: String, function: String, text: String, level: MixpanelLogLevel) { if let file = path.components(separatedBy: "/").last { self.file = file } else { @@ -52,31 +52,31 @@ public struct LogMessage { } /// Any object that conforms to this protocol may log messages -public protocol Logging { - func addMessage(message: LogMessage) +public protocol MixpanelLogging { + func addMessage(message: MixpanelLogMessage) } -public class Logger { - private static var loggers = [Logging]() - private static var enabledLevels = Set() +public class MixpanelLogger { + private static var loggers = [MixpanelLogging]() + private static var enabledLevels = Set() private static let readWriteLock: ReadWriteLock = ReadWriteLock(label: "loggerLock") /// Add a `Logging` object to receive all log messages - public class func addLogging(_ logging: Logging) { + public class func addLogging(_ logging: MixpanelLogging) { readWriteLock.write { loggers.append(logging) } } /// Enable log messages of a specific `LogLevel` to be added to the log - class func enableLevel(_ level: LogLevel) { + class func enableLevel(_ level: MixpanelLogLevel) { readWriteLock.write { enabledLevels.insert(level) } } /// Disable log messages of a specific `LogLevel` to prevent them from being logged - class func disableLevel(_ level: LogLevel) { + class func disableLevel(_ level: MixpanelLogLevel) { readWriteLock.write { enabledLevels.remove(level) } @@ -85,55 +85,55 @@ public class Logger { /// debug: Adds a debug message to the Mixpanel log /// - Parameter message: The message to be added to the log class func debug(message: @autoclosure() -> Any, _ path: String = #file, _ function: String = #function) { - var enabledLevels = Set() + var enabledLevels = Set() readWriteLock.read { enabledLevels = self.enabledLevels } guard enabledLevels.contains(.debug) else { return } - forwardLogMessage(LogMessage(path: path, function: function, text: "\(message())", + forwardLogMessage(MixpanelLogMessage(path: path, function: function, text: "\(message())", level: .debug)) } /// info: Adds an informational message to the Mixpanel log /// - Parameter message: The message to be added to the log class func info(message: @autoclosure() -> Any, _ path: String = #file, _ function: String = #function) { - var enabledLevels = Set() + var enabledLevels = Set() readWriteLock.read { enabledLevels = self.enabledLevels } guard enabledLevels.contains(.info) else { return } - forwardLogMessage(LogMessage(path: path, function: function, text: "\(message())", + forwardLogMessage(MixpanelLogMessage(path: path, function: function, text: "\(message())", level: .info)) } /// warn: Adds a warning message to the Mixpanel log /// - Parameter message: The message to be added to the log class func warn(message: @autoclosure() -> Any, _ path: String = #file, _ function: String = #function) { - var enabledLevels = Set() + var enabledLevels = Set() readWriteLock.read { enabledLevels = self.enabledLevels } guard enabledLevels.contains(.warning) else { return } - forwardLogMessage(LogMessage(path: path, function: function, text: "\(message())", + forwardLogMessage(MixpanelLogMessage(path: path, function: function, text: "\(message())", level: .warning)) } /// error: Adds an error message to the Mixpanel log /// - Parameter message: The message to be added to the log class func error(message: @autoclosure() -> Any, _ path: String = #file, _ function: String = #function) { - var enabledLevels = Set() + var enabledLevels = Set() readWriteLock.read { enabledLevels = self.enabledLevels } guard enabledLevels.contains(.error) else { return } - forwardLogMessage(LogMessage(path: path, function: function, text: "\(message())", + forwardLogMessage(MixpanelLogMessage(path: path, function: function, text: "\(message())", level: .error)) } /// This forwards a `LogMessage` to each logger that has been added - class private func forwardLogMessage(_ message: LogMessage) { + class private func forwardLogMessage(_ message: MixpanelLogMessage) { // Forward the log message to every registered Logging instance - var loggers = [Logging]() + var loggers = [MixpanelLogging]() readWriteLock.read { loggers = self.loggers } diff --git a/Sources/MixpanelPersistence.swift b/Sources/MixpanelPersistence.swift index c6a6a1b0..24f72dc2 100644 --- a/Sources/MixpanelPersistence.swift +++ b/Sources/MixpanelPersistence.swift @@ -139,7 +139,7 @@ class MixpanelPersistence { defaults.set(timedEventsData, forKey: "\(prefix)\(MixpanelUserDefaultsKeys.timedEvents)") defaults.synchronize() } catch { - Logger.warn(message: "Failed to archive timed events") + MixpanelLogger.warn(message: "Failed to archive timed events") } } @@ -154,7 +154,7 @@ class MixpanelPersistence { do { return try NSKeyedUnarchiver.unarchivedObject(ofClasses: archivedClasses, from: timedEventsData) as? InternalProperties ?? InternalProperties() } catch { - Logger.warn(message: "Failed to unarchive timed events") + MixpanelLogger.warn(message: "Failed to unarchive timed events") return InternalProperties() } } @@ -169,7 +169,7 @@ class MixpanelPersistence { defaults.set(superPropertiesData, forKey: "\(prefix)\(MixpanelUserDefaultsKeys.superProperties)") defaults.synchronize() } catch { - Logger.warn(message: "Failed to archive super properties") + MixpanelLogger.warn(message: "Failed to archive super properties") } } @@ -184,7 +184,7 @@ class MixpanelPersistence { do { return try NSKeyedUnarchiver.unarchivedObject(ofClasses: archivedClasses, from: superPropertiesData) as? InternalProperties ?? InternalProperties() } catch { - Logger.warn(message: "Failed to unarchive super properties") + MixpanelLogger.warn(message: "Failed to unarchive super properties") return InternalProperties() } } @@ -355,14 +355,14 @@ class MixpanelPersistence { if #available(iOS 11.0, macOS 10.13, watchOS 4.0, tvOS 11.0, *) { guard let data = try? Data(contentsOf: URL(fileURLWithPath: filePath)), let unarchivedData = try? NSKeyedUnarchiver.unarchivedObject(ofClasses: MixpanelPersistence.archivedClasses, from: data) else { - Logger.info(message: "Unable to read file at path: \(filePath)") + MixpanelLogger.info(message: "Unable to read file at path: \(filePath)") removeArchivedFile(atPath: filePath) return nil } return unarchivedData } else { guard let unarchivedData = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) else { - Logger.info(message: "Unable to read file at path: \(filePath)") + MixpanelLogger.info(message: "Unable to read file at path: \(filePath)") removeArchivedFile(atPath: filePath) return nil } @@ -374,7 +374,7 @@ class MixpanelPersistence { do { try FileManager.default.removeItem(atPath: filePath) } catch let err { - Logger.info(message: "Unable to remove file at path: \(filePath), error: \(err)") + MixpanelLogger.info(message: "Unable to remove file at path: \(filePath), error: \(err)") } } @@ -440,12 +440,12 @@ class MixpanelPersistence { private func unarchiveWithType(_ type: String) -> Any? { let filePath = filePathWithType(type) guard let path = filePath else { - Logger.info(message: "bad file path, cant fetch file") + MixpanelLogger.info(message: "bad file path, cant fetch file") return nil } guard let unarchivedData = unarchiveWithFilePath(path) else { - Logger.info(message: "can't unarchive file") + MixpanelLogger.info(message: "can't unarchive file") return nil } diff --git a/Sources/Network.swift b/Sources/Network.swift index f4620144..9ae2ebd1 100644 --- a/Sources/Network.swift +++ b/Sources/Network.swift @@ -107,8 +107,8 @@ class Network { return nil } - Logger.debug(message: "Fetching URL") - Logger.debug(message: url.absoluteURL) + MixpanelLogger.debug(message: "Fetching URL") + MixpanelLogger.debug(message: url.absoluteURL) var request = URLRequest(url: url) request.httpMethod = resource.method.rawValue request.httpBody = resource.requestBody diff --git a/Sources/PrintLogging.swift b/Sources/PrintLogging.swift index b1c8d4a9..e464d72d 100644 --- a/Sources/PrintLogging.swift +++ b/Sources/PrintLogging.swift @@ -9,16 +9,16 @@ import Foundation /// Simply formats and prints the object by calling `print` -class PrintLogging: Logging { - func addMessage(message: LogMessage) { +class PrintLogging: MixpanelLogging { + func addMessage(message: MixpanelLogMessage) { print("[Mixpanel - \(message.file) - func \(message.function)] (\(message.level.rawValue)) - \(message.text)") } } /// Simply formats and prints the object by calling `debugPrint`, this makes things a bit easier if you /// need to print data that may be quoted for instance. -class PrintDebugLogging: Logging { - func addMessage(message: LogMessage) { +class PrintDebugLogging: MixpanelLogging { + func addMessage(message: MixpanelLogMessage) { debugPrint("[Mixpanel - \(message.file) - func \(message.function)] (\(message.level.rawValue)) - \(message.text)") } } diff --git a/Sources/Track.swift b/Sources/Track.swift index ffc64143..58a172ac 100644 --- a/Sources/Track.swift +++ b/Sources/Track.swift @@ -41,7 +41,7 @@ class Track { if let event = event { ev = event } else { - Logger.info(message: "mixpanel track called with empty event parameter. using 'mp_event'") + MixpanelLogger.info(message: "mixpanel track called with empty event parameter. using 'mp_event'") } if !(mixpanelInstance?.trackAutomaticEventsEnabled ?? false) && ev.hasPrefix("$ae_") { return timedEvents @@ -140,7 +140,7 @@ class Track { } var updatedTimedEvents = timedEvents guard let event = event, !event.isEmpty else { - Logger.error(message: "mixpanel cannot time an empty event") + MixpanelLogger.error(message: "mixpanel cannot time an empty event") return updatedTimedEvents } updatedTimedEvents[event] = startTime @@ -156,7 +156,7 @@ class Track { func clearTimedEvent(event: String?, timedEvents: InternalProperties) -> InternalProperties { var updatedTimedEvents = timedEvents guard let event = event, !event.isEmpty else { - Logger.error(message: "mixpanel cannot clear an empty timed event") + MixpanelLogger.error(message: "mixpanel cannot clear an empty timed event") return updatedTimedEvents } updatedTimedEvents.removeValue(forKey: event) From 650df0ba34a91a7aab4e31c3c8f3bbca0d72fd87 Mon Sep 17 00:00:00 2001 From: Jared McFarland Date: Thu, 30 Jan 2025 12:49:04 -0800 Subject: [PATCH 6/8] rename in MixpanelDemo LoggerTests --- .../MixpanelDemoTests/LoggerTests.swift | 50 +++++++++---------- Sources/MixpanelLogger.swift | 2 +- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift b/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift index 62867bf4..ca8fefd5 100644 --- a/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift +++ b/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift @@ -1,5 +1,5 @@ // -// LoggerTests.swift +// MixpanelLoggerTests.swift // MixpanelDemo // // Created by Sam Green on 7/8/16. @@ -10,68 +10,68 @@ import Foundation import XCTest @testable import Mixpanel -class LoggerTests: XCTestCase { +class MixpanelLoggerTests: XCTestCase { func testEnableDebug() { let counter = CounterLogging() - Logger.addLogging(counter) - Logger.enableLevel(.debug) + MixpanelLogger.addLogging(counter) + MixpanelLogger.enableLevel(.debug) - Logger.debug(message: "logged") + MixpanelLogger.debug(message: "logged") XCTAssertEqual(1, counter.count) } func testEnableInfo() { let counter = CounterLogging() - Logger.addLogging(counter) - Logger.enableLevel(.info) - Logger.info(message: "logged") + MixpanelLogger.addLogging(counter) + MixpanelLogger.enableLevel(.info) + MixpanelLogger.info(message: "logged") XCTAssertEqual(1, counter.count) } func testEnableWarning() { let counter = CounterLogging() - Logger.addLogging(counter) - Logger.enableLevel(.warning) - Logger.warn(message: "logged") + MixpanelLogger.addLogging(counter) + MixpanelLogger.enableLevel(.warning) + MixpanelLogger.warn(message: "logged") XCTAssertEqual(1, counter.count) } func testEnableError() { let counter = CounterLogging() - Logger.addLogging(counter) - Logger.enableLevel(.error) - Logger.error(message: "logged") + MixpanelLogger.addLogging(counter) + MixpanelLogger.enableLevel(.error) + MixpanelLogger.error(message: "logged") XCTAssertEqual(1, counter.count) } func testDisabledLogging() { let counter = CounterLogging() - Logger.addLogging(counter) - Logger.disableLevel(.debug) - Logger.debug(message: "not logged") + MixpanelLogger.addLogging(counter) + MixpanelLogger.disableLevel(.debug) + MixpanelLogger.debug(message: "not logged") XCTAssertEqual(0, counter.count) - Logger.disableLevel(.error) - Logger.error(message: "not logged") + MixpanelLogger.disableLevel(.error) + MixpanelLogger.error(message: "not logged") XCTAssertEqual(0, counter.count) - Logger.disableLevel(.info) - Logger.info(message: "not logged") + MixpanelLogger.disableLevel(.info) + MixpanelLogger.info(message: "not logged") XCTAssertEqual(0, counter.count) - Logger.disableLevel(.warning) - Logger.warn(message: "not logged") + MixpanelLogger.disableLevel(.warning) + MixpanelLogger.warn(message: "not logged") XCTAssertEqual(0, counter.count) } } -/// This is a stub that implements `Logging` to be passed to our `Logger` instance for testing +/// This is a stub that implements `Logging` to be passed to our `MixpanelLogger` instance for testing class CounterLogging: Logging { var count = 0 - func addMessage(message: LogMessage) { + func addMessage(message: MixpanelLogMessage) { count = count + 1 } } diff --git a/Sources/MixpanelLogger.swift b/Sources/MixpanelLogger.swift index 6e1be7ef..44ea71c0 100644 --- a/Sources/MixpanelLogger.swift +++ b/Sources/MixpanelLogger.swift @@ -130,7 +130,7 @@ public class MixpanelLogger { level: .error)) } - /// This forwards a `LogMessage` to each logger that has been added + /// This forwards a `MixpanelLogMessage` to each logger that has been added class private func forwardLogMessage(_ message: MixpanelLogMessage) { // Forward the log message to every registered Logging instance var loggers = [MixpanelLogging]() From 028b5eee7b22e441e709b9f0bfb04fd3c47a7570 Mon Sep 17 00:00:00 2001 From: Jared McFarland Date: Thu, 30 Jan 2025 12:52:14 -0800 Subject: [PATCH 7/8] more renaming --- MixpanelDemo/MixpanelDemoTests/LoggerTests.swift | 4 ++-- Sources/MixpanelInstance.swift | 6 +++--- Sources/MixpanelLogger.swift | 12 ++++++------ 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift b/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift index ca8fefd5..b6f6a8b6 100644 --- a/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift +++ b/MixpanelDemo/MixpanelDemoTests/LoggerTests.swift @@ -67,8 +67,8 @@ class MixpanelLoggerTests: XCTestCase { } } -/// This is a stub that implements `Logging` to be passed to our `MixpanelLogger` instance for testing -class CounterLogging: Logging { +/// This is a stub that implements `MixpanelLogging` to be passed to our `MixpanelLogger` instance for testing +class CounterLogging: MixpanelLogging { var count = 0 func addMessage(message: MixpanelLogMessage) { diff --git a/Sources/MixpanelInstance.swift b/Sources/MixpanelInstance.swift index 77131e32..df51dcc3 100644 --- a/Sources/MixpanelInstance.swift +++ b/Sources/MixpanelInstance.swift @@ -192,16 +192,16 @@ open class MixpanelInstance: CustomDebugStringConvertible, FlushDelegate, AEDele MixpanelLogger.enableLevel(.info) MixpanelLogger.enableLevel(.warning) MixpanelLogger.enableLevel(.error) - MixpanelLogger.info(message: "Logging Enabled") + MixpanelLogger.info(message: "MixpanelLogging Enabled") } else { - MixpanelLogger.info(message: "Logging Disabled") + MixpanelLogger.info(message: "MixpanelLogging Disabled") MixpanelLogger.disableLevel(.debug) MixpanelLogger.disableLevel(.info) MixpanelLogger.disableLevel(.warning) MixpanelLogger.disableLevel(.error) } #if DEBUG - var trackProps: Properties = ["Logging Enabled": loggingEnabled] + var trackProps: Properties = ["MixpanelLogging Enabled": loggingEnabled] if (superProperties["mp_lib"] != nil) { trackProps["mp_lib"] = self.superProperties["mp_lib"] as! String } diff --git a/Sources/MixpanelLogger.swift b/Sources/MixpanelLogger.swift index 44ea71c0..701edd6e 100644 --- a/Sources/MixpanelLogger.swift +++ b/Sources/MixpanelLogger.swift @@ -11,16 +11,16 @@ import Foundation /// This defines the various levels of logging that a message may be tagged with. This allows hiding and /// showing different logging levels at run time depending on the environment public enum MixpanelLogLevel: String { - /// Logging displays *all* logs and additional debug information that may be useful to a developer + /// MixpanelLogging displays *all* logs and additional debug information that may be useful to a developer case debug - /// Logging displays *all* logs (**except** debug) + /// MixpanelLogging displays *all* logs (**except** debug) case info - /// Logging displays *only* warnings and above + /// MixpanelLogging displays *only* warnings and above case warning - /// Logging displays *only* errors and above + /// MixpanelLogging displays *only* errors and above case error } @@ -61,7 +61,7 @@ public class MixpanelLogger { private static var enabledLevels = Set() private static let readWriteLock: ReadWriteLock = ReadWriteLock(label: "loggerLock") - /// Add a `Logging` object to receive all log messages + /// Add a `MixpanelLogging` object to receive all log messages public class func addLogging(_ logging: MixpanelLogging) { readWriteLock.write { loggers.append(logging) @@ -132,7 +132,7 @@ public class MixpanelLogger { /// This forwards a `MixpanelLogMessage` to each logger that has been added class private func forwardLogMessage(_ message: MixpanelLogMessage) { - // Forward the log message to every registered Logging instance + // Forward the log message to every registered MixpanelLogging instance var loggers = [MixpanelLogging]() readWriteLock.read { loggers = self.loggers From e0229cfd499023d860c4692a0c933210234cad42 Mon Sep 17 00:00:00 2001 From: Jared McFarland Date: Thu, 30 Jan 2025 13:39:49 -0800 Subject: [PATCH 8/8] update podfile --- Mixpanel-swift.podspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Mixpanel-swift.podspec b/Mixpanel-swift.podspec index 9d6825d7..97845420 100644 --- a/Mixpanel-swift.podspec +++ b/Mixpanel-swift.podspec @@ -17,7 +17,7 @@ Pod::Spec.new do |s| } s.default_subspec = 'Complete' base_source_files = ['Sources/Network.swift', 'Sources/FlushRequest.swift', 'Sources/PrintLogging.swift', 'Sources/FileLogging.swift', - 'Sources/Logger.swift', 'Sources/JSONHandler.swift', 'Sources/Error.swift', 'Sources/AutomaticProperties.swift', + 'Sources/MixpanelLogger.swift', 'Sources/JSONHandler.swift', 'Sources/Error.swift', 'Sources/AutomaticProperties.swift', 'Sources/Constants.swift', 'Sources/MixpanelType.swift', 'Sources/Mixpanel.swift', 'Sources/MixpanelInstance.swift', 'Sources/Flush.swift','Sources/Track.swift', 'Sources/People.swift', 'Sources/AutomaticEvents.swift', 'Sources/Group.swift',