我正在使用cocoaLumberjack日志框架进行iOS日志记录。为了将日志存储在文件中,我使用了此代码。
DDFileLogger* fileLogger = [[DDFileLogger alloc] init];
fileLogger.rollingFrequency = 60 * 60 * 24;
fileLogger.logFileManager.maximumNumberOfLogFiles = 7;
[DDLog addLogger:fileLogger];
DDLogVerbose(@"hello");
NSLog(@"hihihihihi");
我无法找到存储此代码生成的日志文件的确切位置。有人可以帮我解决这个问题吗?
这里的答案似乎没有考虑到可能有多个日志文件的事实。您可以使用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];
}
}
您可以从连接的设备下载日志文件,也可以直接从应用程序发送。两种方法都在下面描述。
在您引用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翻译。
如果您想获取应用在设备上运行时创建的日志文件,
/AppData/Library/Caches/Logs/
中如果这对你有帮助,那么投票会很好!
如果你正在使用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
控制台和文件。
您可以控制它的存储位置,例如,我有时会将其存储在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];
发现这是最新的:
DDFileLogger *fileLogger = [[DDFileLogger alloc] init];
fileLogger.logFileManager.logsDirectory;//THIS
从官方代码:
默认日志文件管理器。
所有日志文件都放在logsDirectory中。如果未指定特定的logsDirectory,则使用默认目录。在Mac上,它位于〜/ Library / Logs /中。在iPhone上,这是在〜/ Library / Caches / Logs中。日志文件名为“log-.txt”,其中uuid是由集合[0123456789ABCDEF]组成的6字符十六进制。根据maximumNumberOfLogFiles属性自动删除存档的日志文件。
得到了答案
它存储在Library / Application Support / Iphone Simulator /#version no#/ applications /#your application#/ documents / logs / log-3 hex no>
在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];
粘贴此代码的最佳位置是您的AppDelegate.m文件中的- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
。您还应该在AppDelegate.m标头中添加以下代码行:
#import <CocoaLumberjack/CocoaLumberjack.h>
希望它会有所帮助。
为了与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 !")
}
}