使用 cocoaLumberjack 存储日志文件在哪里

发布于 2024-11-16 07:01:03 字数 374 浏览 6 评论 0原文

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

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

[DDLog addLogger:fileLogger];

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

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

I am Using cocoaLumberjack logging framework for iOS logging.
For storing logs in a file I used this code.

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

[DDLog addLogger:fileLogger];

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

I am unable to find where exactly the logfile generated by this code is stored.
Can someone help me with this problem ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

尸血腥色 2024-11-23 07:01:03

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

在 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(["[email protected]"])
        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 ->设备
  3. 在设备列表的左上角,单击已连接的设备。
  4. 在主面板的“已安装的应用程序”部分下,单击运行 CocoaLumberjack 的应用程序。
  5. 在“已安装的应用程序”列表底部,单击齿轮图标,然后单击“下载容器”。
  6. 在 Finder 中,右键单击(显示菜单)保存的 .xcappdata 文件,然后选择显示包内容
  7. 日志文件保存在 /AppData/Library/Caches/Logs/

如果这是的话,投票会很好对你有帮助!

You can download the log files from connected device, or you can send directly from app. Both approaches are described below.

Send log files from app through email, in Swift

Write this in the class where you have a reference to DDFileLogger. I would put this in a custom logger class e.g. 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
    }
}

Then, when user taps on a button to indicate that they want to send the logs,

// 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(["[email protected]"])
        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.
    }
}

This results in a compose email pop-up with an attachment file named diagnostic.log, which is all the log files concatenated together.

Special thanks - This is pretty much a Swift translation from the Objective-C version given by the other answer.

Get log file(s) from device directly, through USB cable

If you want to get the log files that your app created while running on device,

  1. Connect your device to your mac
  2. In Xcode, go to Window -> Devices
  3. On top-left in the device list, click on the connected device.
  4. In the main panel, under Installed Apps section, click on the application in which you ran CocoaLumberjack.
  5. At the bottom of the Installed Apps list, click on the gear icon and then Download Container.
  6. In Finder, right click (show menu) on the saved .xcappdata file and select Show Package Contents
  7. Log files are saved in /AppData/Library/Caches/Logs/

Up-vote would be nice if this is helpful to you!

狠疯拽 2024-11-23 07:01:03

这里的答案似乎没有考虑到可能存在多个日志文件的事实。您可以使用 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:@"[email protected]"]];

        [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];
    }
}

The answers here don't seem to account for the fact that there may be multiple log files. You can use your DDFileLogger instance's logFileManager property to loop through file information. Check out DDFileLogger.h for public methods and properties. The following may be of use:

- (NSString *)logsDirectory;

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

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

Here is my solution for getting log data (and emailing it). Note that the default number of log files is 5 as of this writing.

- (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:@"[email protected]"]];

        [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];
    }
}
×纯※雪 2024-11-23 07:01:03

如果您使用 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

到控制台和文件。

If you're using CocoaLumberjack, you have DDFileLogger.h and you can expose the currentLogFileInfo: method that is implemented already:

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

Then, you can programmatically access the path to the current file with:

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

Which, on my iPhone, printed:

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

to both the console and the file.

匿名的好友 2024-11-23 07:01:03

你可以控制它的存储位置,例如,我有时将它存储在 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];

You can control where it is stored, for example, I sometime store it in the iTunes folder for easy retrieval. Use this in the AppDelegate when setting up the fileLogger:

NSString * applicationDocumentsDirectory = [[[[NSFileManager defaultManager]    
     URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] path];
DDLogFileManagerDefault *documentsFileManager = [[DDLogFileManagerDefault alloc]
     initWithLogsDirectory:applicationDocumentsDirectory];
DDFileLogger *fileLogger = [[DDFileLogger alloc]
     initWithLogFileManager:documentsFileManager];
踏雪无痕 2024-11-23 07:01:03

发现这是最新的:

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

fileLogger.logFileManager.logsDirectory;//THIS

来自官方代码:

默认日志文件管理器。

所有日志文件都放置在logsDirectory 中。如果一个特定的
未指定logsDirectory,使用默认目录。在
Mac,它位于 ~/Library/Logs/ 中。在 iPhone 上,这个
位于 ~/Library/Caches/Logs 中。
日志文件名为“log-.txt”,其中 uuid 是由 [0123456789ABCDEF] 集组成的 6 个字符的十六进制。
归档日志文件将根据maximumNumberOfLogFiles 属性自动删除。

Found this to be the latest:

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

fileLogger.logFileManager.logsDirectory;//THIS

From the official code:

Default log file manager.

All log files are placed inside the logsDirectory. If a specific
logsDirectory isn't specified, the default directory is used. On
Mac, this is in ~/Library/Logs/. On iPhone, this
is in ~/Library/Caches/Logs.
Log files are named "log-.txt", where uuid is a 6 character hexadecimal consisting of the set [0123456789ABCDEF].
Archived log files are automatically deleted according to the maximumNumberOfLogFiles property.

寂寞清仓 2024-11-23 07:01:03

得到答案

它存储在
库/应用程序支持/Iphone Simulator/#version no#/applications/#your application#/documents/logs/log-3hex no>

Got the answer

It is stored in
Library/Appication Support/Iphone Simulator/#version no#/applications/#your application#/documents/logs/log-3hex no>

他不在意 2024-11-23 07:01:03

在 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 protected]"]];

        [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];

粘贴此代码的最佳位置是 - (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
在您的 AppDelegate.m 文件中。
另外,您应该在 AppDelegate.m 标头中添加这行代码:

#import <CocoaLumberjack/CocoaLumberjack.h>

希望它会有所帮助。

Send log files from app through email, in Objective-C

Objective-C code:

In you header:

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

In your implementation:

- (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 protected]"]];

        [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];
}

Here is how you could add something in your Log-file:

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

Don't forget to set your ddLogLevel in your Constants-file.

Constants.h :

extern NSUInteger const ddLogLevel;

Comstants.m :

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

It is very obvious but don't forget to configure CocoaLumberjack in your AppDelegate.m file.

[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];

The best place to paste this code is - (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
in your AppDelegate.m file.
Also you should add this line of code in your AppDelegate.m header:

#import <CocoaLumberjack/CocoaLumberjack.h>

Hope it will help.

穿透光 2024-11-23 07:01:03

我必须稍微重写它才能与 Swift 4 兼容......

var logFileDataArray: [Data] {
    let logFilePaths = delegate.fileLogger.logFileManager.sortedLogFilePaths
    var logFileDataArray = [Data]()
    for logFilePath in logFilePaths {
        let fileURL = URL(fileURLWithPath: logFilePath)
        if let logFileData =
            try? Data(contentsOf: fileURL, options: Data.ReadingOptions.mappedIfSafe) {
            logFileDataArray.insert(logFileData, at: 0)
        }
    }
    return logFileDataArray
}

func sendApplicationLog(text: String) {
    if MFMailComposeViewController.canSendMail() {
        let controller = MFMailComposeViewController()
        controller.mailComposeDelegate = self
        controller.setToRecipients(["[email protected]"])
        controller.setSubject("Log of motorkari iOS")
        controller.setMessageBody(text, isHTML: false)
        var attachmentData = Data()
        for logFileData in logFileDataArray { attachmentData.append(logFileData) }
        controller.addAttachmentData(attachmentData, mimeType: "text/plain",
                                    fileName: "motorkari_ios_application.log")
        present(controller, animated: true, completion: nil)
    } else {
        showMessage("Log cannot be send !")
    }
}

I had to rewrite it a little to be compatible with Swift 4...

var logFileDataArray: [Data] {
    let logFilePaths = delegate.fileLogger.logFileManager.sortedLogFilePaths
    var logFileDataArray = [Data]()
    for logFilePath in logFilePaths {
        let fileURL = URL(fileURLWithPath: logFilePath)
        if let logFileData =
            try? Data(contentsOf: fileURL, options: Data.ReadingOptions.mappedIfSafe) {
            logFileDataArray.insert(logFileData, at: 0)
        }
    }
    return logFileDataArray
}

func sendApplicationLog(text: String) {
    if MFMailComposeViewController.canSendMail() {
        let controller = MFMailComposeViewController()
        controller.mailComposeDelegate = self
        controller.setToRecipients(["[email protected]"])
        controller.setSubject("Log of motorkari iOS")
        controller.setMessageBody(text, isHTML: false)
        var attachmentData = Data()
        for logFileData in logFileDataArray { attachmentData.append(logFileData) }
        controller.addAttachmentData(attachmentData, mimeType: "text/plain",
                                    fileName: "motorkari_ios_application.log")
        present(controller, animated: true, completion: nil)
    } else {
        showMessage("Log cannot be send !")
    }
}
羁拥 2024-11-23 07:01:03

我不知道这是否对其他人有帮助...我接受了之前的答案并将其传递给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)")
    }
}

I don't know if this might help somebody else... I took the previous answers and passed it to Swift 5. Apart from getting all the paths, it prints the content.

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)")
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文