Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding OSLog and Loggly support #498

Merged
merged 1 commit into from
Jun 25, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Loop.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@
432E73CB1D24B3D6009AD15D /* RemoteDataManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 432E73CA1D24B3D6009AD15D /* RemoteDataManager.swift */; };
433EA4C21D9F39C900CD78FB /* PumpIDTableViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 433EA4C11D9F39C900CD78FB /* PumpIDTableViewController.swift */; };
433EA4C41D9F71C800CD78FB /* CommandResponseViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 433EA4C31D9F71C800CD78FB /* CommandResponseViewController.swift */; };
4341F4EB1EDB92AC001C936B /* LogglyService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4341F4EA1EDB92AC001C936B /* LogglyService.swift */; };
43441A9C1EDB34810087958C /* StatusExtensionContext+LoopKit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43441A9B1EDB34810087958C /* StatusExtensionContext+LoopKit.swift */; };
43441AA01EDB4D390087958C /* OSLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43441A9F1EDB4D390087958C /* OSLog.swift */; };
4346D1E71C77F5FE00ABAFE3 /* ChartTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4346D1E61C77F5FE00ABAFE3 /* ChartTableViewCell.swift */; };
4346D1F61C78501000ABAFE3 /* ChartPoint+Loop.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4346D1F51C78501000ABAFE3 /* ChartPoint+Loop.swift */; };
434F54571D287FDB002A9274 /* NibLoadable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 434F54561D287FDB002A9274 /* NibLoadable.swift */; };
Expand Down Expand Up @@ -378,7 +380,9 @@
4337615E1D52F487004A3647 /* GlucoseHUDView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GlucoseHUDView.swift; sourceTree = "<group>"; };
433EA4C11D9F39C900CD78FB /* PumpIDTableViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PumpIDTableViewController.swift; sourceTree = "<group>"; };
433EA4C31D9F71C800CD78FB /* CommandResponseViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CommandResponseViewController.swift; sourceTree = "<group>"; };
4341F4EA1EDB92AC001C936B /* LogglyService.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LogglyService.swift; sourceTree = "<group>"; };
43441A9B1EDB34810087958C /* StatusExtensionContext+LoopKit.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatusExtensionContext+LoopKit.swift"; sourceTree = "<group>"; };
43441A9F1EDB4D390087958C /* OSLog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OSLog.swift; sourceTree = "<group>"; };
4346D1E61C77F5FE00ABAFE3 /* ChartTableViewCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChartTableViewCell.swift; sourceTree = "<group>"; };
4346D1EF1C781BEA00ABAFE3 /* SwiftCharts.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftCharts.framework; path = Carthage/Build/iOS/SwiftCharts.framework; sourceTree = "<group>"; };
4346D1F51C78501000ABAFE3 /* ChartPoint+Loop.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ChartPoint+Loop.swift"; sourceTree = "<group>"; };
Expand Down Expand Up @@ -739,6 +743,7 @@
isa = PBXGroup;
children = (
438849EB1D29EC34003B3F23 /* AmplitudeService.swift */,
4341F4EA1EDB92AC001C936B /* LogglyService.swift */,
438849ED1D2A1EBB003B3F23 /* MLabService.swift */,
438849E91D297CB6003B3F23 /* NightscoutService.swift */,
437CCADF1D285C7B0075D2C3 /* ServiceAuthentication.swift */,
Expand Down Expand Up @@ -842,6 +847,7 @@
43CEE6E51E56AFD400CB9116 /* NightscoutUploader.swift */,
4398973A1CD2FC2000223065 /* NSDateFormatter.swift */,
43E344A31B9E1B1C00C85C07 /* NSUserDefaults.swift */,
43441A9F1EDB4D390087958C /* OSLog.swift */,
43BFF0CA1E466C0900FF19A9 /* StateColorPalette.swift */,
43F41C361D3BF32400C11ED6 /* UIAlertController.swift */,
43BFF0BB1E45C80600FF19A9 /* UIColor+Loop.swift */,
Expand Down Expand Up @@ -1442,6 +1448,7 @@
43776F901B8022E90074EA36 /* AppDelegate.swift in Sources */,
437CCADA1D284ADF0075D2C3 /* AuthenticationTableViewCell.swift in Sources */,
439BED2E1E760BC600B0AED5 /* EnliteCGMManager.swift in Sources */,
4341F4EB1EDB92AC001C936B /* LogglyService.swift in Sources */,
43CE7CDE1CA8B63E003CC1B0 /* Data.swift in Sources */,
43BFF0CB1E466C0900FF19A9 /* StateColorPalette.swift in Sources */,
438991691E91B571000EEF90 /* ChartPoint.swift in Sources */,
Expand Down Expand Up @@ -1500,6 +1507,7 @@
43F41C371D3BF32400C11ED6 /* UIAlertController.swift in Sources */,
433EA4C41D9F71C800CD78FB /* CommandResponseViewController.swift in Sources */,
434F545F1D288345002A9274 /* ShareService.swift in Sources */,
43441AA01EDB4D390087958C /* OSLog.swift in Sources */,
43CEE6E61E56AFD400CB9116 /* NightscoutUploader.swift in Sources */,
4328E0331CFC091100E199AA /* WatchContext+LoopKit.swift in Sources */,
4F526D611DF8D9A900A04910 /* NetBasal.swift in Sources */,
Expand Down
8 changes: 6 additions & 2 deletions Loop/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ final class AppDelegate: UIResponder, UIApplicationDelegate {

NotificationManager.authorize(delegate: self)

AnalyticsManager.sharedManager.application(application, didFinishLaunchingWithOptions: launchOptions)
let bundle = Bundle(for: type(of: self))
DiagnosticLogger.shared = DiagnosticLogger(subsystem: bundle.bundleIdentifier!, version: bundle.shortVersionString)
DiagnosticLogger.shared?.forCategory("AppDelegate").info(#function)

AnalyticsManager.shared.application(application, didFinishLaunchingWithOptions: launchOptions)

if let navVC = window?.rootViewController as? UINavigationController,
let statusVC = navVC.viewControllers.first as? StatusTableViewController {
Expand Down Expand Up @@ -75,7 +79,7 @@ extension AppDelegate: UNUserNotificationCenterDelegate {
let startDate = response.notification.request.content.userInfo[NotificationManager.UserInfoKey.bolusStartDate.rawValue] as? Date,
startDate.timeIntervalSinceNow >= TimeInterval(minutes: -5)
{
AnalyticsManager.sharedManager.didRetryBolus()
AnalyticsManager.shared.didRetryBolus()

deviceManager.enactBolus(units: units, at: startDate) { (_) in
completionHandler()
Expand Down
27 changes: 27 additions & 0 deletions Loop/Extensions/OSLog.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//
// OSLog.swift
// Loop
//
// Copyright © 2017 LoopKit Authors. All rights reserved.
//

import os.log


extension OSLog {
func debug(_ message: StaticString, _ args: CVarArg...) {
log(message, type: .debug, args)
}

func info(_ message: StaticString, _ args: CVarArg...) {
log(message, type: .info, args)
}

func error(_ message: StaticString, _ args: CVarArg...) {
log(message, type: .error, args)
}

private func log(_ message: StaticString, type: OSLogType, _ args: CVarArg...) {
os_log(message, log: self, type: type, args)
}
}
2 changes: 1 addition & 1 deletion Loop/Managers/AnalyticsManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ final class AnalyticsManager {
}
}

static let sharedManager = AnalyticsManager()
static let shared = AnalyticsManager()

// MARK: - Helpers

Expand Down
12 changes: 6 additions & 6 deletions Loop/Managers/DeviceDataManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ final class DeviceDataManager {

// MARK: - Utilities

let logger = DiagnosticLogger()
let logger = DiagnosticLogger.shared!

/// Remember the launch date of the app for diagnostic reporting
fileprivate let launchDate = Date()
Expand Down Expand Up @@ -61,7 +61,7 @@ final class DeviceDataManager {
}

if let oldVal = oldVal, newVal - oldVal >= 0.5 {
AnalyticsManager.sharedManager.pumpBatteryWasReplaced()
AnalyticsManager.shared.pumpBatteryWasReplaced()
}
}
}
Expand Down Expand Up @@ -93,7 +93,7 @@ final class DeviceDataManager {
case is MySentryAlertMessageBody, is MySentryAlertClearedMessageBody:
break
case let body:
logger.addMessage(["messageType": Int(message.messageType.rawValue), "messageBody": body.txData.hexadecimalString], toCollection: "sentryOther")
logger.forCategory("MySentry").info(["messageType": Int(message.messageType.rawValue), "messageBody": body.txData.hexadecimalString])
}
default:
break
Expand All @@ -112,15 +112,15 @@ final class DeviceDataManager {

rileyLinkManager.connectDevice(device)

AnalyticsManager.sharedManager.didChangeRileyLinkConnectionState()
AnalyticsManager.shared.didChangeRileyLinkConnectionState()
}

func disconnectFromRileyLink(_ device: RileyLinkDevice) {
connectedPeripheralIDs.remove(device.peripheral.identifier.uuidString)

rileyLinkManager.disconnectDevice(device)

AnalyticsManager.sharedManager.didChangeRileyLinkConnectionState()
AnalyticsManager.shared.didChangeRileyLinkConnectionState()

if connectedPeripheralIDs.count == 0 {
NotificationManager.clearPendingNotificationRequests()
Expand Down Expand Up @@ -246,7 +246,7 @@ final class DeviceDataManager {
}

if newValue.unitVolume > previousVolume + 1 {
AnalyticsManager.sharedManager.reservoirWasRewound()
AnalyticsManager.shared.reservoirWasRewound()
}
}
}
Expand Down
10 changes: 4 additions & 6 deletions Loop/Managers/DiagnosticLogger+LoopKit.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,14 @@ import LoopKit

extension DiagnosticLogger {
func addError(_ message: String, fromSource source: String) {
let info = [
"source": source,
"message": message,
"reportedAt": DateFormatter.ISO8601StrictDateFormatter().string(from: Date())
let message = [
"message": message
]

addMessage(info, toCollection: "errors")
forCategory(source).error(message)
}

func addError(_ message: Error, fromSource source: String) {
addError(String(describing: message), fromSource: source)
forCategory(source).error(message)
}
}
121 changes: 111 additions & 10 deletions Loop/Managers/DiagnosticLogger.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,135 @@
//

import Foundation
import os.log


final class DiagnosticLogger {
private lazy var isSimulator: Bool = TARGET_OS_SIMULATOR != 0
private let isSimulator: Bool = TARGET_OS_SIMULATOR != 0
let subsystem: String
let version: String

var mLabService: MLabService {
didSet {
try! KeychainManager().setMLabDatabaseName(mLabService.databaseName, APIKey: mLabService.APIKey)
}
}

init() {
var logglyService: LogglyService {
didSet {
try! KeychainManager().setLogglyCustomerToken(logglyService.customerToken)
}
}

let remoteLogLevel: OSLogType

static var shared: DiagnosticLogger?

init(subsystem: String, version: String) {
self.subsystem = subsystem
self.version = version
remoteLogLevel = isSimulator ? .fault : .info

if let (databaseName, APIKey) = KeychainManager().getMLabCredentials() {
mLabService = MLabService(databaseName: databaseName, APIKey: APIKey)
} else {
mLabService = MLabService(databaseName: nil, APIKey: nil)
}

let customerToken = KeychainManager().getLogglyCustomerToken()
logglyService = LogglyService(customerToken: customerToken)
}

func addMessage(_ message: [String: Any], toCollection collection: String) {
if !isSimulator,
let messageData = try? JSONSerialization.data(withJSONObject: message, options: []),
let task = mLabService.uploadTaskWithData(messageData, inCollection: collection)
{
task.resume()
} else {
NSLog("%@: %@", collection, message)
func forCategory(_ category: String) -> CategoryLogger {
return CategoryLogger(logger: self, category: category)
}
}


extension OSLogType {
fileprivate var tagName: String {
switch self {
case let t where t == .info:
return "info"
case let t where t == .debug:
return "debug"
case let t where t == .error:
return "error"
case let t where t == .fault:
return "fault"
default:
return "default"
}
}
}


final class CategoryLogger {
private let logger: DiagnosticLogger
let category: String

private let systemLog: OSLog

fileprivate init(logger: DiagnosticLogger, category: String) {
self.logger = logger
self.category = category

systemLog = OSLog(subsystem: logger.subsystem, category: category)
}

private func remoteLog(_ type: OSLogType, message: String) {
guard logger.remoteLogLevel.rawValue <= type.rawValue else {
return
}

logger.logglyService.client?.send(message, tags: [type.tagName, category])
}

private func remoteLog(_ type: OSLogType, message: [String: Any]) {
guard logger.remoteLogLevel.rawValue <= type.rawValue else {
return
}

logger.logglyService.client?.send(message, tags: [type.tagName, category])

// Legacy mLab logging. To be removed.
if let messageData = try? JSONSerialization.data(withJSONObject: message, options: []) {
logger.mLabService.uploadTaskWithData(messageData, inCollection: category)?.resume()
}
}

func debug(_ message: [String: Any]) {
systemLog.debug("%{public}@", String(describing: message))
remoteLog(.debug, message: message)
}

func debug(_ message: String) {
systemLog.error("%{public}@", message)
remoteLog(.debug, message: message)
}

func info(_ message: [String: Any]) {
systemLog.info("%{public}@", String(describing: message))
remoteLog(.info, message: message)
}

func info(_ message: String) {
systemLog.error("%{public}@", message)
remoteLog(.info, message: message)
}

func error(_ message: [String: Any]) {
systemLog.error("%{public}@", String(reflecting: message))
remoteLog(.error, message: message)
}

func error(_ message: String) {
systemLog.error("%{public}@", message)
remoteLog(.error, message: message)
}

func error(_ error: Error) {
self.error(String(reflecting: error))
}
}

9 changes: 0 additions & 9 deletions Loop/Managers/KeychainManager+Loop.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,11 @@
import Foundation


private let AmplitudeAPIKeyService = "AmplitudeAPIKey"
private let DexcomShareURL = URL(string: "https://share1.dexcom.com")!
private let NightscoutAccount = "NightscoutAPI"


extension KeychainManager {
func setAmplitudeAPIKey(_ key: String?) throws {
try replaceGenericPassword(key, forService: AmplitudeAPIKeyService)
}

func getAmplitudeAPIKey() -> String? {
return try? getGenericPasswordForService(AmplitudeAPIKeyService)
}

func setDexcomShareUsername(_ username: String?, password: String?) throws {
let credentials: InternetCredentials?

Expand Down
Loading