ios 使用 cocoaLumberjack 存储日志文件在哪里
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6411549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where is Logfile stored using cocoaLumberHyman
提问by abhiasawa
I am Using cocoaLumberHyman logging framework for iOS logging. For storing logs in a file I used this code.
我正在使用 cocoaLumberHyman 日志框架进行 iOS 日志记录。为了将日志存储在文件中,我使用了此代码。
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 ?
我无法找到此代码生成的日志文件的确切存储位置。有人可以帮我解决这个问题吗?
采纳答案by abhiasawa
Got the answer
得到了答案
It is stored in Library/Appication Support/Iphone Simulator/#version no#/applications/#your application#/documents/logs/log-3hex no>
它存储在 Library/Appication Support/Iphone Simulator/#version no#/applications/#your application#/documents/logs/log-3hex no>
回答by Kyle Robson
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:
这里的答案似乎没有说明可能有多个日志文件的事实。您可以使用 DDFileLogger 实例的 logFileManager 属性来循环文件信息。查看 DDFileLogger.h 以获取公共方法和属性。以下可能有用:
- (NSString *)logsDirectory; - (NSArray *)unsortedLogFilePaths; - (NSArray *)unsortedLogFileNames; - (NSArray *)unsortedLogFileInfos; - (NSArray *)sortedLogFilePaths; - (NSArray *)sortedLogFileNames; - (NSArray *)sortedLogFileInfos;
- (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.
这是我获取日志数据(并通过电子邮件发送)的解决方案。请注意,在撰写本文时,日志文件的默认数量为 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];
}
}
回答by Daniel
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
在 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
将此写在您引用 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
}
}
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.
这会导致一个带有名为 的附件文件的撰写电子邮件弹出窗口diagnostic.log
,它是连接在一起的所有日志文件。
Special thanks - This is pretty much a Swift translation from the Objective-C version given by the other answer.
特别感谢 - 这几乎是另一个答案给出的 Objective-C 版本的 Swift 翻译。
Get log file(s) from device directly, through USB cable
通过 USB 电缆直接从设备获取日志文件
If you want to get the log files that your app created while running on device,
如果您想获取应用在设备上运行时创建的日志文件,
- Connect your device to your mac
- In Xcode, go to Window -> Devices
- On top-left in the device list, click on the connected device.
- In the main panel, under Installed Apps section, click on the application in which you ran CocoaLumberHyman.
- At the bottom of the Installed Apps list, click on the gear icon and then Download Container.
- In Finder, right click (show menu) on the saved .xcappdata file and select Show Package Contents
- Log files are saved in
/AppData/Library/Caches/Logs/
- 将您的设备连接到您的 Mac
- 在 Xcode 中,转到窗口 -> 设备
- 在设备列表的左上角,单击已连接的设备。
- 在主面板的 Installed Apps 部分下,单击您运行 CocoaLumberHyman 的应用程序。
- 在已安装的应用程序列表底部,单击齿轮图标,然后单击下载容器。
- 在 Finder 中,右键单击(显示菜单)保存的 .xcappdata 文件并选择显示包内容
- 日志文件保存在
/AppData/Library/Caches/Logs/
Up-vote would be nice if this is helpful to you!
如果这对您有帮助,请点赞!
回答by kenichi
If you're using CocoaLumberHyman, you have DDFileLogger.h
and you can expose the currentLogFileInfo:
method that is implemented already:
如果您使用的是 CocoaLumberHyman,那么DDFileLogger.h
您可以公开currentLogFileInfo:
已经实现的方法:
@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:
其中,在我的 iPhone 上,打印:
log file at: /var/mobile/Applications/3BE1219F-78BE-491C-B68C-74D6FA0C2EF1/Library/Caches/Logs/log-5D1286.txt
to both the console and the file.
到控制台和文件。
回答by jpalten
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:
您可以控制它的存储位置,例如,我有时将其存储在 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];
回答by Ravindranath Akila
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.
默认日志文件管理器。
所有日志文件都放在logsDirectory 中。如果未指定特定的 logsDirectory,则使用默认目录。在 Mac 上,它位于 ~/Library/Logs/ 中。在 iPhone 上,它位于 ~/Library/Caches/Logs 中。日志文件被命名为“log-.txt”,其中 uuid 是一个由 [0123456789ABCDEF] 组成的 6 个字符的十六进制。归档的日志文件会根据 maximumNumberOfLogFiles 属性自动删除。
回答by Alexey Pelekh
Send log files from app through email, in Objective-C
在 Objective-C 中通过电子邮件从应用程序发送日志文件
Objective-Ccode:
目标 C代码:
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.
不要忘记ddLogLevel
在您的常量文件中设置您的。
Constants.h :
常量.h:
extern NSUInteger const ddLogLevel;
Comstants.m :
常数.m :
NSUInteger const ddLogLevel =
#ifdef DEBUG
LOG_LEVEL_VERBOSE;
#else
LOG_LEVEL_ERROR;
#endif
It is very obvious but don't forget to configure CocoaLumberHyman in your AppDelegate.mfile.
很明显,但不要忘记在AppDelegate.m文件中配置 CocoaLumberHyman 。
[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.mfile.
Also you should add this line of code in your AppDelegate.mheader:
粘贴此代码的最佳位置是- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
在您的AppDelegate.m文件中。您还应该在AppDelegate.m标头中添加这行代码:
#import <CocoaLumberHyman/CocoaLumberHyman.h>
Hope it will help.
希望它会有所帮助。
回答by Renetik
I had to rewrite it a little to be compatible with Swift 4...
我不得不稍微重写它以与 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 !")
}
}
回答by TomCobo
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.
我不知道这是否对其他人有帮助......我接受了之前的答案并将其传递给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)")
}
}