From e5f07cf1fba0b964a504efa4bc2c872eaaac057e Mon Sep 17 00:00:00 2001 From: Vignesh Kumar Date: Thu, 16 Feb 2017 16:49:07 +0530 Subject: [PATCH] - Coloured output log in Terminal for mac OS. - Support CocoaPods, mac OS and Vapor framework(Swift Package Manager). --- Sources/Loggly.swift | 73 ++- SwiftLoggly.xcodeproj/project.pbxproj | 20 +- SwiftLoggly/Loggly.swift | 710 -------------------------- 3 files changed, 52 insertions(+), 751 deletions(-) delete mode 100644 SwiftLoggly/Loggly.swift diff --git a/Sources/Loggly.swift b/Sources/Loggly.swift index 37ae499..8bbc552 100644 --- a/Sources/Loggly.swift +++ b/Sources/Loggly.swift @@ -53,32 +53,33 @@ extension NSDictionary { //MARK: - Struct for Color Log struct ColorLog { - static let ESCAPE = "\u{001b}[" + + static let ESCAPE = "\u{001B}[" static let RESET_FG = ESCAPE + "fg;" // Clear any foreground color static let RESET_BG = ESCAPE + "bg;" // Clear any background color - static let RESET = ESCAPE + ";" // Clear any foreground or background color + static let RESET = ESCAPE + "0m" // Clear any foreground or background color static func red(object: T) { - print("\(ESCAPE)fg255,0,0;\(object)\(RESET)") + print("\(ESCAPE)31m\(object)\(RESET)") } static func green(object: T) { - print("\(ESCAPE)fg0,255,0;\(object)\(RESET)") + print("\(ESCAPE)32m\(object)\(RESET)") } static func blue(object: T) { - print("\(ESCAPE)fg0,0,255;\(object)\(RESET)") + print("\(ESCAPE)34m\(object)\(RESET)") } static func yellow(object: T) { - print("\(ESCAPE)fg255,255,0;\(object)\(RESET)") + print("\(ESCAPE)33m\(object)\(RESET)") } static func purple(object: T) { - print("\(ESCAPE)fg255,0,255;\(object)\(RESET)") + print("\(ESCAPE)35m\(object)\(RESET)") } - + } //MARK: - Enumaration for log type @@ -92,8 +93,8 @@ public enum LogType { //MARK: - Loggly Class open class Loggly { - - //MARK: - Log Report Properties + + //MARK: - Log Report Properties //The name of swift loggly report. var logReportName = "SwiftLogglyReport"; @@ -160,7 +161,7 @@ open class Loggly { return logReportName; } - func loadLogCounts() { + func loadLogCounts() { if logInfoCount == 0 && logVerboseCount == 0 && logWarnCount == 0 && logDebugCount == 0 && logErrorCount == 0 { self.loadLogDetails() } @@ -178,23 +179,23 @@ open class Loggly { let row = dict as! NSDictionary for key in row.allKeys { switch (key as! String) { - case "Info": - logInfoCount = (row.object(forKey: key) as! NSString).integerValue; - break - case "Verbose": - logVerboseCount = (row.object(forKey: key) as! NSString).integerValue; - break - case "Warnings": - logWarnCount = (row.object(forKey: key) as! NSString).integerValue; - break - case "Debug": - logDebugCount = (row.object(forKey: key) as! NSString).integerValue; - break - case "Error": - logErrorCount = (row.object(forKey: key) as! NSString).integerValue; - break - default : - break + case "Info": + logInfoCount = (row.object(forKey: key) as! NSString).integerValue; + break + case "Verbose": + logVerboseCount = (row.object(forKey: key) as! NSString).integerValue; + break + case "Warnings": + logWarnCount = (row.object(forKey: key) as! NSString).integerValue; + break + case "Debug": + logDebugCount = (row.object(forKey: key) as! NSString).integerValue; + break + case "Error": + logErrorCount = (row.object(forKey: key) as! NSString).integerValue; + break + default : + break } } @@ -260,7 +261,7 @@ open class Loggly { } return count; } - + // Get the Loggly Info Count open func getLogInfoCount() -> NSInteger{ @@ -294,7 +295,7 @@ open class Loggly { let fileManager = FileManager.default if fileManager.fileExists(atPath: path) { return path; - } + } return ""; } @@ -459,9 +460,9 @@ open class Loggly { case .Info: logTypeStr = isEmojis ? "💙 Info - " : "Info - "; case .Verbose: - logTypeStr = isEmojis ? "💜 Verbose - " : "Verbose - "; + logTypeStr = isEmojis ? "💜 Verbose - " : "Verbose - "; case .Warnings: - logTypeStr = isEmojis ? "💛 Warnings - " : "Warnings - "; + logTypeStr = isEmojis ? "💛 Warnings - " : "Warnings - "; case .Debug: logTypeStr = isEmojis ? "💚 Debug - " : "Debug - "; case .Error: @@ -503,8 +504,8 @@ open class Loggly { fileHandle.seekToEndOfFile() fileHandle.write(writeText.data(using: String.Encoding.utf8)!) fileHandle.closeFile() - writeText = "[\(logTypeName(type, isEmojis: true)) \(dateStr)]: \(text)\n" - print(writeText, terminator: "") + writeText = "[\(logTypeName(type, isEmojis: true)) \(dateStr)]: \(text)" + printLog(type, text:writeText) cleanup() } self.increaseLogCount(type); @@ -586,7 +587,7 @@ open class Loggly { ///a free function to make writing to the log with Log type public func getLogglyReportsOutput() -> NSDictionary { - return Loggly.logger.getReportsOutput() + return Loggly.logger.getReportsOutput() } // Before logging details it return empty path. Once logging is done. Method return exact report path @@ -707,5 +708,3 @@ public func loggly(_ type: LogType, dictionary: Dictionary) { public func loggly(_ type: LogType, dictionary: NSDictionary) { Loggly.logger.write(type, text: dictionary.jsonString) } - - diff --git a/SwiftLoggly.xcodeproj/project.pbxproj b/SwiftLoggly.xcodeproj/project.pbxproj index 2f3a75c..92e6c2a 100644 --- a/SwiftLoggly.xcodeproj/project.pbxproj +++ b/SwiftLoggly.xcodeproj/project.pbxproj @@ -11,7 +11,8 @@ 0B3B6C8B1E3F8B48003AE9C4 /* SwiftLogglyOSX.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0B3B6C821E3F8B47003AE9C4 /* SwiftLogglyOSX.framework */; }; 0B3B6C901E3F8B48003AE9C4 /* SwiftLogglyOSXTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B3B6C8F1E3F8B48003AE9C4 /* SwiftLogglyOSXTests.swift */; }; 0B3B6C921E3F8B48003AE9C4 /* SwiftLogglyOSX.h in Headers */ = {isa = PBXBuildFile; fileRef = 0B3B6C841E3F8B47003AE9C4 /* SwiftLogglyOSX.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 0B41130B1E55AA1B00ADEE0F /* Loggly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B41130A1E55AA1B00ADEE0F /* Loggly.swift */; }; + 0B411B2C1E55C13400ADEE0F /* Loggly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B411B2B1E55C13400ADEE0F /* Loggly.swift */; }; + 0B411B2D1E55C13400ADEE0F /* Loggly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B411B2B1E55C13400ADEE0F /* Loggly.swift */; }; 0B6915701E4DB54B007C9394 /* SwiftLoggly.h in Headers */ = {isa = PBXBuildFile; fileRef = 0B3B6C001E3F6221003AE9C4 /* SwiftLoggly.h */; }; 0B6915781E4DB71F007C9394 /* SwiftLogglyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B6915771E4DB71F007C9394 /* SwiftLogglyTests.swift */; }; 0B69157A1E4DB71F007C9394 /* SwiftLoggly.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0B3B6BFD1E3F6221003AE9C4 /* SwiftLoggly.framework */; }; @@ -44,7 +45,7 @@ 0B3B6C8A1E3F8B48003AE9C4 /* SwiftLogglyOSXTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SwiftLogglyOSXTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 0B3B6C8F1E3F8B48003AE9C4 /* SwiftLogglyOSXTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwiftLogglyOSXTests.swift; sourceTree = ""; }; 0B3B6C911E3F8B48003AE9C4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 0B41130A1E55AA1B00ADEE0F /* Loggly.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Loggly.swift; sourceTree = ""; }; + 0B411B2B1E55C13400ADEE0F /* Loggly.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Loggly.swift; sourceTree = ""; }; 0B6915751E4DB71F007C9394 /* SwiftLogglyTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SwiftLogglyTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 0B6915771E4DB71F007C9394 /* SwiftLogglyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwiftLogglyTests.swift; sourceTree = ""; }; 0B6915791E4DB71F007C9394 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; @@ -109,7 +110,7 @@ 0B3B6BFF1E3F6221003AE9C4 /* SwiftLoggly */ = { isa = PBXGroup; children = ( - 0B41130A1E55AA1B00ADEE0F /* Loggly.swift */, + 0B411B2A1E55C13400ADEE0F /* Sources */, 0B3B6C001E3F6221003AE9C4 /* SwiftLoggly.h */, 0B3B6C011E3F6221003AE9C4 /* Info.plist */, ); @@ -134,6 +135,14 @@ path = SwiftLogglyOSXTests; sourceTree = ""; }; + 0B411B2A1E55C13400ADEE0F /* Sources */ = { + isa = PBXGroup; + children = ( + 0B411B2B1E55C13400ADEE0F /* Loggly.swift */, + ); + path = Sources; + sourceTree = SOURCE_ROOT; + }; 0B6915761E4DB71F007C9394 /* SwiftLogglyTests */ = { isa = PBXGroup; children = ( @@ -327,7 +336,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 0B41130B1E55AA1B00ADEE0F /* Loggly.swift in Sources */, + 0B411B2C1E55C13400ADEE0F /* Loggly.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -335,6 +344,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 0B411B2D1E55C13400ADEE0F /* Loggly.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -578,6 +588,7 @@ 0B3B6C971E3F8B48003AE9C4 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; DEVELOPMENT_TEAM = 7FUQA46NH7; @@ -594,6 +605,7 @@ 0B3B6C981E3F8B48003AE9C4 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; CODE_SIGN_IDENTITY = "-"; COMBINE_HIDPI_IMAGES = YES; DEVELOPMENT_TEAM = 7FUQA46NH7; diff --git a/SwiftLoggly/Loggly.swift b/SwiftLoggly/Loggly.swift deleted file mode 100644 index 8bbc552..0000000 --- a/SwiftLoggly/Loggly.swift +++ /dev/null @@ -1,710 +0,0 @@ -// -// Loggly.swift -// SwiftLoggly -// -// Created by Vignesh on 30/01/17. -// Copyright © 2017 vigneshuvi. All rights reserved. -// - -import Foundation - - -//MARK: - Extension for String to find length -extension String { - var length: Int { - return self.characters.count - } -} - -//MARK: - Extension for convert Dictionary to String -extension Dictionary { - var jsonString: String { - let invalidJson = "Not a valid JSON" - do { - let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) - return String(bytes: jsonData, encoding: String.Encoding.utf8) ?? invalidJson - } catch { - return invalidJson - } - } - - func printJson() { - print(jsonString) - } -} - - -//MARK: - Extension for convert NSDictionary to String -extension NSDictionary { - var jsonString: String { - let invalidJson = "Not a valid JSON" - do { - let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) - return String(bytes: jsonData, encoding: String.Encoding.utf8) ?? invalidJson - } catch { - return invalidJson - } - } - - func printJson() { - print(jsonString) - } -} - -//MARK: - Struct for Color Log -struct ColorLog { - - static let ESCAPE = "\u{001B}[" - - static let RESET_FG = ESCAPE + "fg;" // Clear any foreground color - static let RESET_BG = ESCAPE + "bg;" // Clear any background color - static let RESET = ESCAPE + "0m" // Clear any foreground or background color - - static func red(object: T) { - print("\(ESCAPE)31m\(object)\(RESET)") - } - - static func green(object: T) { - print("\(ESCAPE)32m\(object)\(RESET)") - } - - static func blue(object: T) { - print("\(ESCAPE)34m\(object)\(RESET)") - } - - static func yellow(object: T) { - print("\(ESCAPE)33m\(object)\(RESET)") - } - - static func purple(object: T) { - print("\(ESCAPE)35m\(object)\(RESET)") - } - -} - -//MARK: - Enumaration for log type -public enum LogType { - case Info - case Verbose - case Warnings - case Debug - case Error -} - -//MARK: - Loggly Class -open class Loggly { - - //MARK: - Log Report Properties - - //The name of swift loggly report. - var logReportName = "SwiftLogglyReport"; - - //The field of loggly report. - var logReportFields:NSArray = ["Info", "Verbose", "Warnings", "Debug", "Error"] - - //The field of Info Count - var logInfoCount:NSInteger = 0 - - //The field of Verbose Count - var logVerboseCount:NSInteger = 0 - - //The field of Warnings Count - var logWarnCount:NSInteger = 0 - - //The field of Debug Count - var logDebugCount:NSInteger = 0 - - //The field of Error Count - var logErrorCount:NSInteger = 0 - - //MARK: - Log Properties - - ///The max size a log file can be in Kilobytes. Default is 1024 (1 MB) - open var maxFileSize: UInt64 = 1024; - - ///The max number of log file that will be stored. Once this point is reached, the oldest file is deleted. - open var maxFileCount = 4; - - ///The directory in which the log files will be written - open var directory = Loggly.defaultDirectory(); - - //The name of the log files. - open var name = "logglyfile"; - - //The date format of the log time. - open var logDateFormat = ""; - - ///logging singleton - open class var logger: Loggly { - - struct Static { - static let instance: Loggly = Loggly() - } - Static.instance.loadLogCounts() - return Static.instance - } - - //MARK: - Reports Util Methods - - ///gets the CSV name - func getReportFileName() -> String { - return "\(logReportName).csv" - } - - // Set the Loggly Reports Name - open func setLogglyReportsName(_ name: String){ - logReportName = name; - } - - // Get the Loggly Reports Name - open func getLogglyReportsName() -> String{ - return logReportName; - } - - func loadLogCounts() { - if logInfoCount == 0 && logVerboseCount == 0 && logWarnCount == 0 && logDebugCount == 0 && logErrorCount == 0 { - self.loadLogDetails() - } - } - - func loadLogDetails() { - let path = "\(directory)/\(getReportFileName())" - let fileManager = FileManager.default - if fileManager.fileExists(atPath: path) { - let logDict:NSMutableDictionary = self.readReports(); - if logDict.allKeys.count > 0 { - let rows:NSArray = logDict.object(forKey: "rows") as! NSArray; - if rows.count > 0 { - for dict in rows { - let row = dict as! NSDictionary - for key in row.allKeys { - switch (key as! String) { - case "Info": - logInfoCount = (row.object(forKey: key) as! NSString).integerValue; - break - case "Verbose": - logVerboseCount = (row.object(forKey: key) as! NSString).integerValue; - break - case "Warnings": - logWarnCount = (row.object(forKey: key) as! NSString).integerValue; - break - case "Debug": - logDebugCount = (row.object(forKey: key) as! NSString).integerValue; - break - case "Error": - logErrorCount = (row.object(forKey: key) as! NSString).integerValue; - break - default : - break - } - - } - } - } - } - } - } - - // Set the Loggly Reports Name - func increaseLogCount(_ type: LogType){ - switch type { - case .Info: - logInfoCount += 1; - case .Verbose: - logVerboseCount += 1; - case .Warnings: - logWarnCount += 1; - case .Debug: - logDebugCount += 1; - case .Error: - logErrorCount += 1; - } - - _ = self.createCSVReport(self.generateReportArray()) - } - - func generateReportArray() -> NSMutableArray { - // Create Dictionary object for storing log count - let logDictforCount:NSMutableDictionary = self.getReportsOutput() - // CSV rows Array - let data:NSMutableArray = NSMutableArray() - data.add(logDictforCount); - return data; - } - - func getReportsOutput() -> NSMutableDictionary { - - // Create Dictionary object for storing log count - let logDictforCount:NSMutableDictionary = NSMutableDictionary() - logDictforCount.setObject(logInfoCount, forKey: "Info" as NSCopying); - logDictforCount.setObject(logVerboseCount, forKey: "Verbose" as NSCopying); - logDictforCount.setObject(logWarnCount, forKey: "Warnings" as NSCopying); - logDictforCount.setObject(logDebugCount, forKey: "Debug" as NSCopying); - logDictforCount.setObject(logErrorCount, forKey: "Error" as NSCopying); - return logDictforCount; - } - - // Get the Loggly Info Count - func getCountBasedonLogType(_ type: LogType) -> NSInteger{ - var count:NSInteger = 0; - switch type { - case .Info: - count = self.getLogInfoCount(); - case .Verbose: - count = self.getLogVerboseCount(); - case .Warnings: - count = self.getLogWarningsCount(); - case .Debug: - count = self.getLogDebugCount(); - case .Error: - count = self.getLogErrorCount(); - } - return count; - } - - - // Get the Loggly Info Count - open func getLogInfoCount() -> NSInteger{ - return logInfoCount; - } - - // Get the Loggly Verbose Count - open func getLogVerboseCount() -> NSInteger{ - return logVerboseCount; - } - - // Get the Loggly Warnings Count - open func getLogWarningsCount() -> NSInteger{ - return logWarnCount; - } - - // Get the Loggly Debug Count - open func getLogDebugCount() -> NSInteger{ - return logDebugCount; - } - - // Get the Loggly Error Count - open func getLogErrorCount() -> NSInteger{ - return logErrorCount; - } - - - ///write content to the current csv file. - open func getReportsFilePath() -> String{ - let path = "\(directory)/\(getReportFileName())" - let fileManager = FileManager.default - if fileManager.fileExists(atPath: path) { - return path; - } - return ""; - } - - func createCSVReport(_ values: NSArray) -> String { - if logReportFields.count > 0 && values.count > 0 { - let path = "\(directory)/\(getReportFileName())" - let fileManager = FileManager.default - if !fileManager.fileExists(atPath: path) { - do { - try "".write(toFile: path, atomically: true, encoding: String.Encoding.utf8) - } catch _ { - } - } else { - do { - try "".write(toFile: path, atomically: true, encoding: String.Encoding.utf8) - } catch _ { - } - } - - let result:String = logReportFields.componentsJoined(by: ","); - Loggly.logger.writeReports( text: result) - for dict in values { - let values = (dict as! NSDictionary).allValues as NSArray; - let result:String = values.componentsJoined(by: ","); - Loggly.logger.writeReports( text: result) - } - return Loggly.logger.getReportsFilePath(); - } - return ""; - } - - ///write content to the current csv file. - open func writeReports(text: String) { - let path = "\(directory)/\(getReportFileName())" - let fileManager = FileManager.default - if !fileManager.fileExists(atPath: path) { - do { - try "".write(toFile: path, atomically: true, encoding: String.Encoding.utf8) - } catch _ { - } - } - if let fileHandle = FileHandle(forWritingAtPath: path) { - let writeText = "\(text)\n" - fileHandle.seekToEndOfFile() - fileHandle.write(writeText.data(using: String.Encoding.utf8)!) - fileHandle.closeFile() - } - } - - open func readReports() -> NSMutableDictionary { - let path = "\(directory)/\(getReportFileName())" - return self.readFromPath(filePath:path); - } - - /// read content to the current csv file. - open func readFromPath(filePath: String) -> NSMutableDictionary{ - let fileManager = FileManager.default - let output:NSMutableDictionary = NSMutableDictionary() - - // Find the CSV file path is available - if fileManager.fileExists(atPath: filePath) { - do { - // Generate the Local file path URL - let localPathURL: URL = NSURL.fileURL(withPath: filePath); - - // Read the content from Local Path - let csvText = try String(contentsOf: localPathURL, encoding: String.Encoding.utf8); - - // Check the csv count - if csvText.characters.count > 0 { - - // Split based on Newline delimiter - let csvArray = self.splitUsingDelimiter(csvText, separatedBy: "\n") as NSArray - if csvArray.count >= 2 { - var fieldsArray:NSArray = []; - let rowsArray:NSMutableArray = NSMutableArray() - for row in csvArray { - // Get the CSV headers - if((row as! String).contains(csvArray[0] as! String)) { - fieldsArray = self.splitUsingDelimiter(row as! String, separatedBy: ",") as NSArray; - } else { - // Get the CSV values - let valuesArray = self.splitUsingDelimiter(row as! String, separatedBy: ",") as NSArray; - if valuesArray.count == fieldsArray.count && valuesArray.count > 0{ - let rowJson:NSMutableDictionary = self.generateDict(fieldsArray, valuesArray: valuesArray) - if rowJson.allKeys.count > 0 && valuesArray.count == rowJson.allKeys.count && rowJson.allKeys.count == fieldsArray.count { - rowsArray.add(rowJson) - } - } - } - } - - // Set the CSV headers & Values and name in the dict. - if fieldsArray.count > 0 && rowsArray.count > 0 { - output.setObject(fieldsArray, forKey: "fields" as NSCopying) - output.setObject(rowsArray, forKey: "rows" as NSCopying) - output.setObject(localPathURL.lastPathComponent, forKey: "name" as NSCopying) - } - } - } - } - catch { - /* error handling here */ - print("Error while read csv: \(error)", terminator: "") - } - } - return output; - } - - func generateDict(_ fieldsArray: NSArray, valuesArray: NSArray ) -> NSMutableDictionary { - let rowsDictionary:NSMutableDictionary = NSMutableDictionary() - for i in 0.. NSArray { - if string.characters.count > 0 { - return string.components(separatedBy: separatedBy) as NSArray; - } - return []; - } - - ///do the checks and cleanup - open func cleanupReports() { - let path = "\(directory)/\(getReportFileName())" - let size = fileSize(path) - if size > 0 { - //delete the oldest file - let deletePath = "\(directory)/\(getReportFileName())" - let fileManager = FileManager.default - do { - try fileManager.removeItem(atPath: deletePath) - } catch _ { - } - } - } - - //MARK: - Loggly Util Methods - - //the date formatter - var dateFormatter: DateFormatter { - let formatter = DateFormatter() - if !logDateFormat.isEmpty && logDateFormat.length > 0 { - formatter.dateFormat = logDateFormat - } else { - formatter.timeStyle = .medium - formatter.dateStyle = .medium - } - return formatter - } - - ///gets the log type with String - // use colored Emojis for better visual distinction - // of log level for Xcode 8 - func logTypeName(_ type: LogType, isEmojis:Bool) -> String { - var logTypeStr = ""; - switch type { - case .Info: - logTypeStr = isEmojis ? "💙 Info - " : "Info - "; - case .Verbose: - logTypeStr = isEmojis ? "💜 Verbose - " : "Verbose - "; - case .Warnings: - logTypeStr = isEmojis ? "💛 Warnings - " : "Warnings - "; - case .Debug: - logTypeStr = isEmojis ? "💚 Debug - " : "Debug - "; - case .Error: - logTypeStr = isEmojis ? "❤️ Error - " : "Error - "; - } - - return logTypeStr; - } - - /// Prints the log type with String and type color code. - func printLog(_ type: LogType, text:String) { - switch type { - case .Info: - ColorLog.blue(object: text) - case .Verbose: - ColorLog.purple(object: text) - case .Warnings: - ColorLog.yellow(object: text) - case .Debug: - ColorLog.green(object: text) - case .Error: - ColorLog.red(object: text) - } - } - - ///write content to the current log file. - open func write(_ type: LogType, text: String) { - let path = "\(directory)/\(logName(0))" - let fileManager = FileManager.default - if !fileManager.fileExists(atPath: path) { - do { - try "".write(toFile: path, atomically: true, encoding: String.Encoding.utf8) - } catch _ { - } - } - if let fileHandle = FileHandle(forWritingAtPath: path) { - let dateStr = dateFormatter.string(from: Date()) - var writeText = "[\(logTypeName(type, isEmojis: false)) \(dateStr)]: \(text)\n" - fileHandle.seekToEndOfFile() - fileHandle.write(writeText.data(using: String.Encoding.utf8)!) - fileHandle.closeFile() - writeText = "[\(logTypeName(type, isEmojis: true)) \(dateStr)]: \(text)" - printLog(type, text:writeText) - cleanup() - } - self.increaseLogCount(type); - } - - ///do the checks and cleanup - func cleanup() { - let path = "\(directory)/\(logName(0))" - let size = fileSize(path) - let maxSize: UInt64 = maxFileSize*1024 - if size > 0 && size >= maxSize && maxSize > 0 && maxFileCount > 0 { - rename(0) - //delete the oldest file - let deletePath = "\(directory)/\(logName(maxFileCount))" - let fileManager = FileManager.default - do { - try fileManager.removeItem(atPath: deletePath) - } catch _ { - } - } - } - - ///check the size of a file - func fileSize(_ path: String) -> UInt64 { - let fileManager = FileManager.default - if fileManager.fileExists(atPath: path) { - let attrs: NSDictionary? = try! fileManager.attributesOfItem(atPath: path) as NSDictionary? - if let dict = attrs { - return dict.fileSize() - } - } - return 0 - } - - ///Recursive method call to rename log files - func rename(_ index: Int) { - let fileManager = FileManager.default - let path = "\(directory)/\(logName(index))" - let newPath = "\(directory)/\(logName(index+1))" - if fileManager.fileExists(atPath: newPath) { - rename(index+1) - } - do { - try fileManager.moveItem(atPath: path, toPath: newPath) - } catch _ { - } - } - - ///gets the log name - func logName(_ num :Int) -> String { - return "\(name)-\(num).log" - } - - ///get the default log directory - class func defaultDirectory() -> String { - var path = "" - let fileManager = FileManager.default - #if os(iOS) - let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) - path = "\(paths[0])/Logs" - #elseif os(OSX) - let urls = fileManager.urls(for: .libraryDirectory, in: .userDomainMask) - if let url = urls.last?.path { - path = "\(url)/Logs" - } - #endif - if !fileManager.fileExists(atPath: path) && path != "" { - do { - try fileManager.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil) - } catch _ { - } - } - return path - } - -} - -//MARK: - Loggly Util Methods - -///a free function to make writing to the log with Log type -public func getLogglyReportsOutput() -> NSDictionary { - return Loggly.logger.getReportsOutput() -} - -// Before logging details it return empty path. Once logging is done. Method return exact report path -public func getLogglyReportCSVfilPath() -> String { - return Loggly.logger.getReportsFilePath() -} - -// Get the Loggly Info Count -public func getLogCountBasedonType(_ type: LogType) -> NSInteger{ - return Loggly.logger.getCountBasedonLogType(type); -} - -//MARK: - Loggly Info Methods - -///a free function to make writing to the log -public func logglyInfo(text: String) { - Loggly.logger.write(LogType.Info, text: text) -} - -///a free function to make writing to the log with Log type -public func logglyInfo(_ dictionary: Dictionary) { - Loggly.logger.write(LogType.Info, text: dictionary.jsonString) -} - -///a free function to make writing to the log with Log type -public func logglyInfo(_ dictionary: NSDictionary) { - Loggly.logger.write(LogType.Info, text: dictionary.jsonString) -} - -//MARK: - Loggly Warning Methods -///a free function to make writing to the log -public func logglyWarnings(text: String) { - Loggly.logger.write(LogType.Warnings, text: text) -} - -///a free function to make writing to the log with Log type -public func logglyWarnings(_ dictionary: Dictionary) { - Loggly.logger.write(LogType.Warnings, text: dictionary.jsonString) -} - -///a free function to make writing to the log with Log type -public func logglyWarnings(_ dictionary: NSDictionary) { - Loggly.logger.write(LogType.Warnings, text: dictionary.jsonString) -} - -//MARK: - Loggly Verbose Methods -///a free function to make writing to the log -public func logglyVerbose(text: String) { - Loggly.logger.write(LogType.Debug, text: text) -} - -///a free function to make writing to the log with Log type -public func logglyVerbose(_ dictionary: Dictionary) { - Loggly.logger.write(LogType.Debug, text: dictionary.jsonString) -} - -///a free function to make writing to the log with Log type -public func logglyVerbose(_ dictionary: NSDictionary) { - Loggly.logger.write(LogType.Debug, text: dictionary.jsonString) -} - -//MARK: - Loggly Debug Methods -///a free function to make writing to the log -public func logglyDebug(text: String) { - Loggly.logger.write(LogType.Debug, text: text) -} - -///a free function to make writing to the log with Log type -public func logglyDebug(_ dictionary: Dictionary) { - Loggly.logger.write(LogType.Debug, text: dictionary.jsonString) -} - -///a free function to make writing to the log with Log type -public func logglyDebug(_ dictionary: NSDictionary) { - Loggly.logger.write(LogType.Debug, text: dictionary.jsonString) -} - -//MARK: - Loggly Error Methods -///a free function to make writing to the log -public func logglyError(text: String) { - Loggly.logger.write(LogType.Error, text: text) -} - -///a free function to make writing to the log with Log type -public func logglyError(_ dictionary: Dictionary) { - Loggly.logger.write(LogType.Error, text: dictionary.jsonString) -} - -///a free function to make writing to the log with Log type -public func logglyError(_ dictionary: NSDictionary) { - Loggly.logger.write(LogType.Error, text: dictionary.jsonString) -} - -///a free function to make writing to the log with Log type -public func logglyError(_ error: NSError) { - Loggly.logger.write(LogType.Error, text: error.localizedDescription) -} - -///a free function to make writing to the log with Log type -public func logglyError(_ error: Error) { - Loggly.logger.write(LogType.Error, text: error.localizedDescription) -} - - -//MARK: - Loggly Methods with Log type - -///a free function to make writing to the log with Log type -public func loggly(_ type: LogType, text: String) { - Loggly.logger.write(type, text: text) -} - -///a free function to make writing to the log with Log type -public func loggly(_ type: LogType, dictionary: Dictionary) { - Loggly.logger.write(type, text: dictionary.jsonString) -} - -///a free function to make writing to the log with Log type -public func loggly(_ type: LogType, dictionary: NSDictionary) { - Loggly.logger.write(type, text: dictionary.jsonString) -}