使用cocoaLumberjack存储Logfile的位置

时间:2011-06-20 13:02:06

标签: ios objective-c logging lumberjack ddfilelogger

我正在使用cocoaLumberjack日志记录框架进行iOS日志记录。 为了将日志存储在文件中,我使用了这段代码。

DDFileLogger* fileLogger = [[DDFileLogger alloc] init];
fileLogger.rollingFrequency = 60 * 60 * 24; 
fileLogger.logFileManager.maximumNumberOfLogFiles = 7;

[DDLog addLogger:fileLogger];

DDLogVerbose(@"hello");
NSLog(@"hihihihihi");

我无法找到存储此代码生成的日志文件的确切位置。 有人可以帮我解决这个问题吗?

8 个答案:

答案 0 :(得分:63)

这里的答案似乎并未考虑到可能存在多个日志文件的事实。您可以使用DDFileLogger实例的logFileManager属性来循环访问文件信息。查看DDFileLogger.h以获取公共方法和属性。以下可能有用:

- (NSString *)logsDirectory;

- (NSArray *)unsortedLogFilePaths;
- (NSArray *)unsortedLogFileNames;
- (NSArray *)unsortedLogFileInfos;

- (NSArray *)sortedLogFilePaths;
- (NSArray *)sortedLogFileNames;
- (NSArray *)sortedLogFileInfos;

这是我获取日志数据(并通过电子邮件发送)的解决方案。请注意,截至本文撰写时,默认的日志文件数为5。

- (NSMutableArray *)errorLogData {
    NSUInteger maximumLogFilesToReturn = MIN([KRLogManager sharedInstance].fileLogger.logFileManager.maximumNumberOfLogFiles, 10);
    NSMutableArray *errorLogFiles = [NSMutableArray arrayWithCapacity:maximumLogFilesToReturn];
    DDFileLogger *logger = [KRLogManager sharedInstance].fileLogger;
    NSArray *sortedLogFileInfos = [logger.logFileManager sortedLogFileInfos];
    for (int i = 0; i < MIN(sortedLogFileInfos.count, maximumLogFilesToReturn); i++) {
        DDLogFileInfo *logFileInfo = [sortedLogFileInfos objectAtIndex:i];
        NSData *fileData = [NSData dataWithContentsOfFile:logFileInfo.filePath];
        [errorLogFiles addObject:fileData];
    }
    return errorLogFiles;
}

- (void)composeEmailWithDebugAttachment {
    if ([MFMailComposeViewController canSendMail]) {

        MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
        mailViewController.mailComposeDelegate = self;
        NSMutableData *errorLogData = [NSMutableData data];
        for (NSData *errorLogFileData in [self errorLogData]) {
            [errorLogData appendData:errorLogFileData];
        }
        [mailViewController addAttachmentData:errorLogData mimeType:@"text/plain" fileName:@"errorLog.txt"];
        [mailViewController setSubject:NSLocalizedString(@"Good Subject", @"")];
        [mailViewController setToRecipients:[NSArray arrayWithObject:@"some@email.com"]];

        [self presentModalViewController:mailViewController animated:YES];

    }

    else {
        NSString *message = NSLocalizedString(@"Sorry, your issue can't be reported right now. This is most likely because no mail accounts are set up on your mobile device.", @"");
        [[[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"") otherButtonTitles: nil] show];
    }
}

答案 1 :(得分:59)

您可以从已连接的设备下载日志文件,也可以直接从应用程序发送。两种方法都在下面描述。

在Swift

中通过电子邮件从应用程序发送日志文件

在您有DDFileLogger引用的类中写这个。我会把它放在自定义记录器类中,例如MyLogger.swift

var ddFileLogger: DDFileLogger!

var logFileDataArray: [NSData] {
    get {
        let logFilePaths = ddFileLogger.logFileManager.sortedLogFilePaths() as! [String]
        var logFileDataArray = [NSData]()
        for logFilePath in logFilePaths {
            let fileURL = NSURL(fileURLWithPath: logFilePath)
            if let logFileData = try? NSData(contentsOfURL: fileURL, options: NSDataReadingOptions.DataReadingMappedIfSafe) {
                // Insert at front to reverse the order, so that oldest logs appear first.
                logFileDataArray.insert(logFileData, atIndex: 0)
            }
        }
        return logFileDataArray
    }
}

然后,当用户点击按钮以指示他们想要发送日志时,

// Required by MFMailComposeViewController
import MessageUI

@IBAction func writeEmailTapped(sender: AnyObject) {
    if MFMailComposeViewController.canSendMail() {
        let composeVC = MFMailComposeViewController()
        composeVC.mailComposeDelegate = self

        // Configure the fields of the interface.
        composeVC.setToRecipients(["your-email@company.com"])
        composeVC.setSubject("Feedback for app")
        composeVC.setMessageBody("", isHTML: false)

        let attachmentData = NSMutableData()
        for logFileData in MyLogger.sharedInstance.logFileDataArray {
            attachmentData.appendData(logFileData)
        }
        composeVC.addAttachmentData(attachmentData, mimeType: "text/plain", fileName: "diagnostic.log")
        self.presentViewController(composeVC, animated: true, completion: nil)
    } else {
        // Tell user about not able to send email directly.
    }
}

这会导致撰写电子邮件弹出窗口,其中包含名为diagnostic.log的附件文件,该文件是连接在一起的所有日志文件。

特别感谢 - 这是另一个答案给出的Objective-C版本的Swift翻译。

通过USB线

直接从设备获取日志文件

如果您想获取应用在设备上运行时创建的日志文件,

  1. 将您的设备连接到Mac
  2. 在Xcode中,转到Window - &gt;设备
  3. 在设备列表的左上角,单击已连接的设备。
  4. 在主面板的“已安装的应用程序”部分下,单击运行CocoaLumberjack的应用程序。
  5. 在“已安装的应用程序”列表的底部,单击齿轮图标,然后单击“下载容器”。
  6. 在Finder中,右键单击(显示菜单)保存的.xcappdata文件,然后选择显示包内容
  7. 日志文件保存在/AppData/Library/Caches/Logs/
  8. 如果这对你有帮助,那么向上投票会很好!

答案 2 :(得分:29)

如果你正在使用CocoaLumberjack,那么你有DDFileLogger.h,你可以公开已经实现的currentLogFileInfo:方法:

@interface DDFileLogger : DDAbstractLogger <DDLogger>
...
- (DDLogFileInfo *)currentLogFileInfo;
@end

然后,您可以使用以下命令以编程方式访问当前文件的路径:

// configure logger
DDFileLogger *fileLogger = [DDFileLogger new];
[DDLog addLogger:fileLogger];
[DDLog addLogger:[DDTTYLogger sharedInstance]];
DDLogInfo(@"log file at: %@", [[fileLogger currentLogFileInfo] filePath]);

在我的iPhone上打印出来:

log file at: /var/mobile/Applications/3BE1219F-78BE-491C-B68C-74D6FA0C2EF1/Library/Caches/Logs/log-5D1286.txt

同时控制台和文件。

答案 3 :(得分:15)

您可以控制它的存储位置,例如,我有时会将其存储在iTunes文件夹中以便于检索。在设置fileLogger时,在AppDelegate中使用它:

NSString * applicationDocumentsDirectory = [[[[NSFileManager defaultManager]    
     URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] path];
DDLogFileManagerDefault *documentsFileManager = [[DDLogFileManagerDefault alloc]
     initWithLogsDirectory:applicationDocumentsDirectory];
DDFileLogger *fileLogger = [[DDFileLogger alloc]
     initWithLogFileManager:documentsFileManager];

答案 4 :(得分:8)

发现这是最新的:

DDFileLogger *fileLogger = [[DDFileLogger alloc] init];

fileLogger.logFileManager.logsDirectory;//THIS

从官方代码:

  

默认日志文件管理器。

     

所有日志文件都放在logsDirectory中。如果具体的话   没有指定logsDirectory,使用默认目录。上   Mac,这是在〜/ Library / Logs /中。在iPhone上,这个   在〜/ Library / Caches / Logs中。        日志文件命名为&#34; log-.txt&#34;,其中uuid是由集合[0123456789ABCDEF]组成的6字符十六进制。        根据maximumNumberOfLogFiles属性自动删除存档的日志文件。

答案 5 :(得分:6)

得到了答案

存储在 图书馆/应用支持/ Iphone模拟器/#版本号#/ applications /#您的应用程序#/ documents / logs / log-3hex no&gt;

答案 6 :(得分:4)

通过电子邮件在Objective-C中发送日志文件

Objective-C 代码:

在你的标题中:

#import <MessageUI/MessageUI.h>
#import "DDLog.h"
#import "DDFileLogger.h"

在您的实施中:

- (NSMutableArray *)errorLogData {
    DDFileLogger *ddFileLogger = [DDFileLogger new];
    NSArray <NSString *> *logFilePaths = [ddFileLogger.logFileManager sortedLogFilePaths];
    NSMutableArray <NSData *> *logFileDataArray = [NSMutableArray new];
    for (NSString* logFilePath in logFilePaths) {
        NSURL *fileUrl = [NSURL fileURLWithPath:logFilePath];
        NSData *logFileData = [NSData dataWithContentsOfURL:fileUrl options:NSDataReadingMappedIfSafe error:nil];
        if (logFileData) {
            [logFileDataArray insertObject:logFileData atIndex:0];
        }
    }
    return logFileDataArray;
}

- (void)composeEmailWithDebugAttachment {
    if ([MFMailComposeViewController canSendMail]) {

        MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
        mailViewController.mailComposeDelegate = self;
        NSMutableData *errorLogData = [NSMutableData data];
        for (NSData *errorLogFileData in [self errorLogData]) {
            [errorLogData appendData:errorLogFileData];
        }
        [mailViewController addAttachmentData:errorLogData mimeType:@"text/plain" fileName:@"filename.log"];
        [mailViewController setSubject:NSLocalizedString(@"LogFile Subject", @"")];
        [mailViewController setToRecipients:[NSArray arrayWithObject:@"email@email.com"]];

        [self presentViewController:mailViewController animated:YES completion:nil];

    } else {
        NSString *message = NSLocalizedString(@"Sorry, your issue can't be reported right now. This is most likely because no mail accounts are set up on your mobile device.", @"");
        [[[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"") otherButtonTitles: nil] show];
    }
}

- (void)mailComposeController:(MFMailComposeViewController *)mailer didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    [self becomeFirstResponder];
    [mailer dismissViewControllerAnimated:YES completion:nil];
}

以下是在日志文件中添加内容的方法:

DDLogError(@"This is an error.");
DDLogWarn(@"This is a warning.");
DDLogInfo(@"This is just a message.");
DDLogVerbose(@"This is a verbose message.");

不要忘记在常量文件中设置ddLogLevel

Constants.h:

extern NSUInteger const ddLogLevel;

Comstants.m:

NSUInteger const ddLogLevel =
#ifdef DEBUG
LOG_LEVEL_VERBOSE;
#else
LOG_LEVEL_ERROR;
#endif

非常明显,但不要忘记在 AppDelegate.m 文件中配置CocoaLumberjack。

[DDLog addLogger:[DDASLLogger sharedInstance]];
[DDLog addLogger:[DDTTYLogger sharedInstance]];

DDFileLogger *fileLogger = [[DDFileLogger alloc] init];
[fileLogger setMaximumFileSize:(1024 * 1024)];
[fileLogger setRollingFrequency:(3600.0 * 24.0)];
[[fileLogger logFileManager] setMaximumNumberOfLogFiles:7];
[DDLog addLogger:fileLogger];

粘贴此代码的最佳位置是 AppDelegate.m 文件中的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;。 您还应该在 AppDelegate.m 标题中添加以下代码:

#import <CocoaLumberjack/CocoaLumberjack.h>

希望它会有所帮助。

答案 7 :(得分:0)

我不知道这是否对其他人有帮助...我接受了先前的答案,并将其传递给了 Swift 5 。除了获取所有路径之外,它还会打印内容。

let logFileLogger = DDFileLogger()
print(logFileLogger.logFileManager.logsDirectory)

for path in logFileLogger.logFileManager.sortedLogFilePaths {
    do {
        let content = try String(contentsOfFile: path, encoding: .utf8)
        print(content)
    } catch let error as NSError {
        print("Error: \(error.localizedDescription)")
    }
}