0

我关注了这篇文章https://github.com/CocoaLumberjack/CocoaLumberjack/issues/439,我能够在我的服务扩展类中完成日志记录。这就是我所做的 -

import CocoaLumberJackSwift

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
let fileManager = FileManager.default
    let appGroupId = Bundle.main.infoDictionary?["APP_GROUP_ID"] as! String
    let containerURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: appGroupId)
    
    let extensionLogDirectory = containerURL?.appendingPathComponent("AppExtensionLogs").path
    
    let logFileManager = DDLogFileManagerDefault.init(logsDirectory: extensionLogDirectory)
    let fileLogger: DDFileLogger = DDFileLogger.init(logFileManager: logFileManager)
    fileLogger.rollingFrequency = 0
    fileLogger.maximumFileSize = 1 * 1024 * 1024
    fileLogger.logFileManager.maximumNumberOfLogFiles = 2
    DDLog.add(fileLogger)
}

然后使用 DDLogDebug 消息,我可以看到日志已登录到此处创建的文件中的 1 个 -

/private/var/mobile/Containers/Shared/AppGroup/1FF0E277-6CBF-4139-8535-AD18B9CFC164/AppExtensionLogs/

现在对此有一些观察-

  1. 有时我会看到日志被切断,打印两次,这有点令人困惑。
  2. 有时即使创建了日志文件,但我在其中看不到任何日志。

这是我用来检索日志的方法 -

 NSString *appGroupId = [NSBundle mainBundle].infoDictionary[@"APP_GROUP_ID"];
  NSURL *containerPathURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:appGroupId];
    
  NSString* extensionLogDirectory = [[containerPathURL URLByAppendingPathComponent:(@"AppExtensionLogs")] path];
    
  NSArray *directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:extensionLogDirectory error:nil];
  AFDebug(@"Logging Started");
  for (NSString* file in directoryContents) {
    NSString *path = [extensionLogDirectory stringByAppendingPathComponent:file];
    NSString *fileContents = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    AFDebug(@"File contents of %@ \n%@", path, fileContents);
  }
  NSLog(@"Logging Stopped");

有人可以帮我吗?有什么我做错了吗?谢谢!!

4

0 回答 0