Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. private let datadogQueue: DispatchQueue = DispatchQueue(label: "foo.datadog")
  2.  
  3. class Logger {
  4. fileprivate var buffer = [NSDictionary]()
  5. fileprivate var backgroundTaskIdentifier: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid
  6. fileprivate var observer: NSObjectProtocol?
  7. // ...
  8.  
  9. init() {
  10. // ...
  11. // This ensures when the user quits the app or puts in background we send the logs to server
  12. observer = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "UIApplicationWillResignActiveNotification"), object: nil, queue: nil, using: {
  13. [unowned self] note in
  14. let tmpbuffer = self.buffer
  15. self.buffer = [NSDictionary]()
  16. self.backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(withName: "saveDatadogLogRecords",
  17. expirationHandler: {
  18. self.endBackgroundTask()
  19. })
  20. self.sendLogsInBuffer(buffer: tmpbuffer)
  21. })
  22. }
  23.  
  24. deinit {
  25. if let observer = observer {
  26. NotificationCenter.default.removeObserver(observer)
  27. }
  28. }
  29.  
  30. func log<T>( _ message: @autoclosure () -> T, level: LogLevel, filename: String, line: Int) {
  31. // logic to convert given parameters to a dictionary
  32. addLogToBuffer(dict)
  33. }
  34.  
  35. private func addLogToBuffer(_ dict: NSDictionary) {
  36. datadogQueue.async {
  37. self.buffer.append(dict)
  38. if self.buffer.count > DatadogConfig.maxEntriesInBuffer { // DatadogConfig.maxEntriesInBuffer = 25 entries
  39. let tmpbuffer = self.buffer
  40. self.buffer = [NSDictionary]()
  41. self.sendLogsInBuffer(buffer: tmpbuffer)
  42. }
  43. }
  44. }
  45.  
  46. private func sendLogsInBuffer(buffer: [NSDictionary]) {
  47. // logic to send logs to server
  48. }
  49.  
  50. private func endBackgroundTask() {
  51. if self.backgroundTaskIdentifier != UIBackgroundTaskIdentifier.invalid {
  52. let value = UIBackgroundTaskIdentifier(rawValue: self.backgroundTaskIdentifier.rawValue)
  53. UIApplication.shared.endBackgroundTask(value)
  54. self.backgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid
  55. print("Ending background task")
  56. }
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement