在平常的APP开发过程中经常碰到程序遇到异常闪退的问题,通过日志可以把相关的详细错误信息进行记录,本实例要记录不管在哪个页面出错都要进行记录,这边使用到的日志记录插件CocoaLumberjack,以文本的形式记录错误信息,然后再去读取各个文本的内容进行展示;当然现在有很多第三方的插件比如友盟也已经集成错误记录的功能;

效果图如下:

1:封装DDLogger的类

MyFileLogger.h文件

#import <Foundation/Foundation.h>
#import <CocoaLumberjack.h> @interface MyFileLogger : NSObject
@property (nonatomic, strong, readwrite) DDFileLogger *fileLogger; +(MyFileLogger *)sharedManager; @end
MyFileLogger.m文件

#import "MyFileLogger.h"

@implementation MyFileLogger

#pragma mark - Inititlization
- (instancetype)init
{
self = [super init]; if (self) {
[self configureLogging];
}
return self;
} #pragma mark 单例模式 static MyFileLogger *sharedManager=nil; +(MyFileLogger *)sharedManager
{
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedManager=[[self alloc]init];
});
return sharedManager;
} #pragma mark - 配记日志类型 - (void)configureLogging
{
#ifdef DEBUG
[DDLog addLogger:[DDASLLogger sharedInstance]];
[DDLog addLogger:[DDTTYLogger sharedInstance]];
#endif
[DDLog addLogger:self.fileLogger];
} #pragma mark - 初始化文件记录类型 - (DDFileLogger *)fileLogger
{
if (!_fileLogger) {
DDFileLogger *fileLogger = [[DDFileLogger alloc] init];
fileLogger.rollingFrequency = 60 * 60 * 24; // 24 hour rolling
fileLogger.logFileManager.maximumNumberOfLogFiles = 7; _fileLogger = fileLogger;
} return _fileLogger;
}
@end

这边是设置24小时进行记录一个文件

2:出进异常进行记录

MyExceptionHandler.h文件

#import <Foundation/Foundation.h>
#import <CocoaLumberjack.h> @interface MyExceptionHandler : NSObject + (void)setDefaultHandler;
+ (NSUncaughtExceptionHandler *)getHandler;
+ (void)TakeException:(NSException *) exception; @end
#import "MyExceptionHandler.h"

void UncaughtExceptionHandler(NSException * exception)
{
NSArray * arr = [exception callStackSymbols];
NSString * reason = [exception reason];
NSString * name = [exception name];
NSString * url = [NSString stringWithFormat:@"========异常错误报告========\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",name,reason,[arr componentsJoinedByString:@"\n"]];
DDLogError(@"%@\n\n",url);
} @implementation MyExceptionHandler + (void)setDefaultHandler
{
NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
} + (NSUncaughtExceptionHandler *)getHandler
{
return NSGetUncaughtExceptionHandler();
} + (void)TakeException:(NSException *)exception
{
NSArray * arr = [exception callStackSymbols];
NSString * reason = [exception reason];
NSString * name = [exception name];
NSString * url = [NSString stringWithFormat:@"========异常错误报告========\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",name,reason,[arr componentsJoinedByString:@"\n"]];
DDLogError(@"%@",url);
}
@end

这个文件也是当出现异常会执行

3:AppDelegate配置的内容

AppDelegate.h文件内容

#import <UIKit/UIKit.h>
#import <DDLog.h>
#import <CocoaLumberjack.h>
#import "MyExceptionHandler.h"
#import "MyFileLogger.h" @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window;
@property (nonatomic, strong) MyFileLogger *logger; @end
AppDelegate.m文件:

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

static const int ddLogLevel = LOG_LEVEL_VERBOSE;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//初始化
[MyExceptionHandler setDefaultHandler];
self.logger=[[MyFileLogger alloc]init]; NSString *path = NSHomeDirectory();//主目录
NSLog(@"当前项目的路径:%@",path); return YES;
} - (void)applicationWillResignActive:(UIApplication *)application {
} - (void)applicationDidEnterBackground:(UIApplication *)application { } - (void)applicationWillEnterForeground:(UIApplication *)application {
} - (void)applicationDidBecomeActive:(UIApplication *)application {
} - (void)applicationWillTerminate:(UIApplication *)application {
} @end

这边重点是设置DDLOG的记录等级ddLogLevel,以及上面两个文件的初始化[MyExceptionHandler setDefaultHandler];self.logger=[[MyFileLogger alloc]init];

实现上面的代码已经能够记录异常的内容;

4:创建一个错误的异常代码

- (void)viewDidLoad {
[super viewDidLoad]; NSArray *test=@[@"123",@"444"];
id testID=test[5];
}

执行到这段代码便记录异常的内容,接着进行内容的展示,是以一个列表展示每个日志文件,然后一个详细页面进行展示;

5:日志列表

loggerTableViewController.h文件

#import <UIKit/UIKit.h>
#import <CocoaLumberjack.h>
#import "AppDelegate.h"
#import "LoggerDetailViewController.h" @interface loggerTableViewController : UIViewController @end
#import "loggerTableViewController.h"

#define BLSRecyclingRecordViewController_CellIdentifier @"MyTablecell"

@interface loggerTableViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (strong, nonatomic) UITableView *myTableView;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, weak) DDFileLogger *fileLogger;
@property (nonatomic, strong) NSArray *logFiles;
@end @implementation loggerTableViewController - (void)viewDidLoad {
[super viewDidLoad]; //加载日志文件
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
_fileLogger = delegate.logger.fileLogger; [self loadLogFiles]; if (!_myTableView) {
_myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height) style:UITableViewStyleGrouped];
_myTableView.showsVerticalScrollIndicator = NO;
_myTableView.showsHorizontalScrollIndicator=NO;
_myTableView.dataSource = self;
_myTableView.delegate = self;
[_myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:BLSRecyclingRecordViewController_CellIdentifier];
[self.view addSubview:_myTableView];
}
} //读取日志的文件个数
- (void)loadLogFiles
{
self.logFiles = self.fileLogger.logFileManager.sortedLogFileInfos;
} //时间格式
- (NSDateFormatter *)dateFormatter
{
if (_dateFormatter) {
return _dateFormatter;
}
_dateFormatter = [[NSDateFormatter alloc] init];
[_dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
return _dateFormatter;
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
} #pragma mark - Table view data source - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
if (section==0) {
return 40;
}
return 10;
} - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 1;
} - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2;
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0) {
return self.logFiles.count;
} return 1;
} - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 30)];
if (section==0) {
UILabel *myLabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, [[UIScreen mainScreen] bounds].size.width, 30)];
myLabel.text=@"日记列表";
[headView addSubview:myLabel];
} return headView;
} - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:BLSRecyclingRecordViewController_CellIdentifier];
if (indexPath.section == 0) {
DDLogFileInfo *logFileInfo = (DDLogFileInfo *)self.logFiles[indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = indexPath.row == 0 ? NSLocalizedString(@"当前", @"") : [self.dateFormatter stringFromDate:logFileInfo.creationDate];
cell.textLabel.textAlignment = NSTextAlignmentLeft;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
cell.textLabel.textAlignment = NSTextAlignmentCenter;
cell.textLabel.text = NSLocalizedString(@"清理旧的记录", @"");
}
return cell;
} #pragma mark - Table view delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES]; if (indexPath.section == 0) {
DDLogFileInfo *logFileInfo = (DDLogFileInfo *)self.logFiles[indexPath.row];
NSData *logData = [NSData dataWithContentsOfFile:logFileInfo.filePath];
NSString *logText = [[NSString alloc] initWithData:logData encoding:NSUTF8StringEncoding]; LoggerDetailViewController *detailViewController = [[LoggerDetailViewController alloc] initWithLog:logText
forDateString:[self.dateFormatter stringFromDate:logFileInfo.creationDate]];
[self.navigationController pushViewController:detailViewController animated:YES];
} else {
for (DDLogFileInfo *logFileInfo in self.logFiles) {
//除了当前 其它进行清除
if (logFileInfo.isArchived) {
[[NSFileManager defaultManager] removeItemAtPath:logFileInfo.filePath error:nil];
}
} [self loadLogFiles];
[self.myTableView reloadData];
}
} @end

这边把表格分成两部分,一部分是日志文件的列表,以及一个清除功能,清除功能主要是对先前的文件进行删除的操作,读取日志的个数及日志时间,日志详细内容

DDLogFileInfo

6:异常的详细信息页面

LoggerDetailViewController.h代码

#import <UIKit/UIKit.h>

@interface LoggerDetailViewController : UIViewController

- (id)initWithLog:(NSString *)logText forDateString:(NSString *)logDate;
@end
LoggerDetailViewController.m文件

#import "LoggerDetailViewController.h"

@interface LoggerDetailViewController ()
@property (nonatomic, strong) NSString *logText;
@property (nonatomic, strong) NSString *logDate;
@property (nonatomic, strong) UITextView *textView;
@end @implementation LoggerDetailViewController - (void)viewDidLoad {
[super viewDidLoad]; self.textView = [[UITextView alloc] initWithFrame:self.view.bounds];
self.textView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
self.textView.editable = NO;
self.textView.text = self.logText;
[self.view addSubview:self.textView];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (id)initWithLog:(NSString *)logText forDateString:(NSString *)logDate
{
self = [super initWithNibName:nil bundle:nil];
if (self) {
_logText = logText;
_logDate = logDate;
self.title = logDate;
}
return self;
} @end

7:如果有第三方其它记录异常的使用,最好用DEBUG模式本地记录异常日志,不然日志只会被记录在一个地方

    //友盟统计加载
[HYBUMAnalyticsHelper UMAnalyticStart]; #ifdef DEBUG
//日志框架(放在其它SDK下面 MyExceptionHandler)
[MyExceptionHandler setDefaultHandler];
#else #endif [MyFileLogger sharedManager];

这样便可以实现不管在哪个页面出出异常都可以进行记录,因为实例比较小,如果要源代码可以留下邮箱统一进行发送;

IOS异常日志记录与展现功能的更多相关文章

  1. Log4Net异常日志记录在asp.net mvc3.0的应用

    前言 log4net是.Net下一个非常优秀的开源日志记录组件.log4net记录日志的功能非常强大.它可以将日志分不同的等级,以不同的格式,输出到不同的媒介.本文主要是简单的介绍如何在Visual ...

  2. Log4Net异常日志记录在asp.net mvc3.0的应用(转载)

    这篇博客写的很好:http://www.cnblogs.com/qianlifeng/archive/2011/04/22/2024856.html 前言 log4net是.Net下一个非常优秀的开源 ...

  3. IOS本地日志记录方案

    我们在项目中日志记录这块也算是比较重要的,有时候用户程序出什么问题,光靠服务器的日志还不能准确的找到问题. 现在一般记录日志有几种方式: 1.使用第三方工具来记录日志,如腾讯的Bugly,它是只把程序 ...

  4. 从壹开始前后端分离 [.netCore 不定期更新 ] 三十五║ 完美实现全局异常日志记录

    缘起 哈喽我是不定期更新的日常,昨天群里小伙伴问到了记录日志,当然,以前我也挖过这个坑,后来一直没有来得及填上,也想着 swagger 一直又有错误信息展示的功能,就迟迟没有添加这个功能,不过昨天夜里 ...

  5. IOS本地日志记录解决方案

    我们在项目中日志记录这块也算是比较重要的,有时候用户程序出什么问题,光靠服务器的日志还不能准确的找到问题 现在一般记录日志有几种方式: 1.使用第三方工具来记录日志,如腾讯的Bugly,它是只把程序的 ...

  6. ASP.NET全局错误处理和异常日志记录以及IIS配置自定义错误页面

    应用场景和使用目的 很多时候,我们在访问页面的时候,由于程序异常.系统崩溃会导致出现黄页.在通常的情况下,黄页对于我们来说,帮助是极大的,因为它可以帮助我们知道问题根源,甚至是哪一行代码出现了错误.但 ...

  7. OneAPM大讲堂 | Java 异常日志记录最佳实践

    [编者按]本文作者是 Casey Dunham.Casey 是一位具有 10 多年经验的专业软件开发人员,以其独特的方式应对应用安全问题而闻名.本文系国内 ITOM 管理平台 OneAPM 工程师编译 ...

  8. 转:使用log4net完成程序异常日志记录(使用SQLite数据库记录和普通文本记录)

    http://www.cnblogs.com/kyo-yo/archive/2010/06/11/use-log4net-to-log-exception.html 在前端时间开发的时候由于需要将异常 ...

  9. ASP.NET Web API 异常日志记录

    如果在 ASP.NET MVC 应用程序中记录异常信息,我们只需要在 Global.asax 的 Application_Error 中添加代码就可以了,比如: public class MvcApp ...

随机推荐

  1. AppStore下载慢的真实原因

    今天有个朋友说他的app下载很慢,他说下载其他的不会,就他的会很慢很卡.我心想这东西苹果的我也没办法了呀,不过我心里也想我平时下载挺快的呀.于是就开始试试.搜索了几个app下载发现确实是有快有慢,并且 ...

  2. Cwinux源码解析(一)

    我在我的个人博客发表了新的文章,欢迎各位读者批评指正. Cwinux源码解析(一)

  3. maven pox.xml 设置主入口配置节点

    <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven ...

  4. 后端码农谈前端(HTML篇)第三课:常见属性

    一.HTML全局属性 1.核心属性 属性 描述 id 设置元素的唯一 id. class 设置元素的一个或多个类名(引用样式表中的类). style 设置元素的行内样式(CSS内联样式). title ...

  5. UML系列03之 UML类图(二)

    概要 在"UML系列02之 UML类图(一) "中介绍了类图的基本构成--类的UML表示方法.本文是接着前文,继续对"UML的类图"中几种关系进行介绍.介绍的主 ...

  6. centos mongodb安装及简单实例

    1.创建目录并设置写权限的操作如下: $mkdir -p /data/db (创建目录和必要的父目录,若父目录不存在则先创建父目录再创建子目录) $ chown -R $usergroup:$user ...

  7. Vim杂记:markdown插件

    一.安装插件 从以下地址下载压缩包 github下载:https://github.com/plasticboy/vim-markdown plasticboy下载:http://plasticboy ...

  8. 第一个sprint总结和读后感

    总结:通过第一个sprint的冲刺,了解了sprint的整个流程,学会了在一个团队里该如何开展一个项目和分配任务.我们的队团在第一个sprint中没有达到我们预期的效果,我们也做出了反省,原因一是我们 ...

  9. SQL Server分布式数据库技术(LinkedServer,CT,SSB)

    SQL Server自定义业务功能的数据同步 在不同业务需求的驱动下,数据库的模块化拆分将会面临一些比较特殊的业务逻辑处理需求.例如,在数据库层面的数据同步需求.同步过程中,可能会有一些比较复杂的业务 ...

  10. LeetCode - 44. Wildcard Matching

    44. Wildcard Matching Problem's Link --------------------------------------------------------------- ...