iOS exception logging and presentation features

Source: Internet
Author: User
Tags uikit

In the common application development process often encountered the problem of abnormal flash, through the log can be related to the detailed error information record, this instance to record regardless of which page error is to be recorded, this side used to the log record plug-in Cocoalumberjack, Record the error message as text, and then read the contents of each text to display; Of course, there are a lot of third-party plug-ins, such as Friends of the League has also integrated the function of error logging;

As follows:

1: Class for encapsulating Ddlogger

MyFileLogger.h file #import <Foundation/Foundation.h> #import <CocoaLumberjack.h> @interface Myfilelogger: Nsobject@property (Nonatomic, Strong, ReadWrite) Ddfilelogger *filelogger;+ (Myfilelogger *) Sharedmanager; @end
MYFILELOGGER.M file #import "MyFileLogger.h" @implementation myfilelogger#pragma mark-inititlization-(instancetype)        init{self = [super init];    if (self) {[self configurelogging]; } return self;}    #pragma mark Singleton mode static Myfilelogger *sharedmanager=nil;+ (Myfilelogger *) sharedmanager{static dispatch_once_t once;    Dispatch_once (&once, ^{sharedmanager=[[self Alloc]init];    }); return Sharedmanager;}    #pragma mark-Record log type-(void) configurelogging{#ifdef DEBUG [Ddlog Addlogger:[ddasllogger sharedinstance]]; [Ddlog Addlogger:[ddttylogger sharedinstance]; #endif [Ddlog AddLogger:self.fileLogger];} #pragma mark-Initialize the file record type-(Ddfilelogger *) filelogger{if (!_filelogger) {Ddfilelogger *filelogger = [[Ddfilelog]        Ger Alloc] init]; filelogger.rollingfrequency = 60 * 60 * 24;                Hour rolling fileLogger.logFileManager.maximumNumberOfLogFiles = 7;    _filelogger = FileLogger; } return _filelogger;} @end

This way is set 24 hours to record a file

2: Out of the exception to record

MyExceptionHandler.h file #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 callst    Acksymbols];    NSString * reason = [exception reason];    NSString * name = [exception name]; NSString * url = [NSString stringwithformat:@ "======== exception error Report ========\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:@ "======== exception error Report ========\nname:%@\nreason:\n%@\ncallstacksymbols:\n%@",    Name,reason,[arr componentsjoinedbystring:@ "\ n"]; Ddlogerror (@ "%@", url);} @end

This file is also executed when an exception occurs

3:contents of appdelegate configuration

AppDelegate.h file contents #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 file: #import "AppDelegate.h" @interface appdelegate () @end @implementation appdelegatestatic const INT Ddloglevel = log_level_verbose;-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: ( Nsdictionary *) launchoptions {    //Initialize    [Myexceptionhandler Setdefaulthandler];    Self.logger=[[myfilelogger Alloc]init];        NSString *path = Nshomedirectory ();//main directory    NSLog (@ "Path of current project:%@", path);        return YES;} -(void) Applicationwillresignactive: (uiapplication *) application {}-(void) Applicationdidenterbackground: ( UIApplication *) application {}-(void) Applicationwillenterforeground: (uiapplication *) application {}-(void) Applicationdidbecomeactive: (uiapplication *) application {}-(void) Applicationwillterminate: (UIApplication *) Application {} @end

The focus here is to set the record level of the Ddlog Ddloglevel, as well as the initialization of the above two files [myexceptionhandler setdefaulthandler]; Self. Logger=[[myfilelogger alloc]init];

Implementation of the above code has been able to record the contents of the exception;

4: Create an incorrect exception code

-(void) viewdidload {    [super viewdidload];        Nsarray *[email protected][@ "123", @ "444"];    ID testid=test[5];}

Execution to this code will record the contents of the exception, followed by the content of the display, is a list of each log file, and then a detailed page to display;

5: Log List

LoggerTableViewController.h file #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];    Load log file Appdelegate *delegate = (appdelegate *) [[uiapplication sharedapplication] delegate];        _filelogger = Delegate.logger.fileLogger;        [Self loadlogfiles]; if (!_mytableview) {_mytableview = [[UITableView alloc] Initwithframe:cgrectmake (0, 0, [[UIScreen Mainscreen] Boun        Ds].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]; }}//number of files read log-(void) loadlogfiles{self.logfiles = Self.fileLogger.logFileManager.sortedLogFileInfos;}    Time Format-(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) {RE    Turn 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 (Ten, [[UIScreen mainscreen] bounds].        Size.width, 30)];        [email protected] "Diary list";    [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 (@ "current", @ ""): [Self.dateformatter stringFromDate:logFileInfo.creationDate];    Cell.textLabel.textAlignment = Nstextalignmentleft;        } else {cell.accessorytype = Uitableviewcellaccessorynone;        Cell.textLabel.textAlignment = Nstextalignmentcenter;    Cell.textLabel.text = nslocalizedstring (@ "Clean up the old record", @ ""); } 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.dateform        Atter StringFromDate:logFileInfo.creationDate]];    [Self.navigationcontroller Pushviewcontroller:detailviewcontroller Animated:yes]; } else {for (Ddlogfileinfo *logfileinfo in self.logfiles) {//except for the current other purge if (logfileinfo.is            Archived) {[[Nsfilemanager Defaultmanager] RemoveItemAtPath:logFileInfo.filePath Error:nil];        }} [self loadlogfiles];    [Self.mytableview Reloaddata]; }} @end

This way, the table is divided into two parts, a list of log files, and a clear function, clear function is mainly to delete the previous files, read the number of logs and log time, log details

Ddlogfileinfo

6: Exception Details page

LoggerDetailViewController.h code #import <UIKit/UIKit.h> @interface Loggerdetailviewcontroller: uiviewcontroller-(ID) Initwithlog: (NSString *) LogText fordatestring: (NSString *) logdate; @end
LOGGERDETAILVIEWCONTROLLER.M file #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 the 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: If there are third-party other records of the use of abnormal, it is best to use Debug mode local log exception logs, otherwise the log will only be recorded in one place

    Friends League statistics loading    [Hybumanalyticshelper Umanalyticstart];        #ifdef DEBUG    //Log framework (Myexceptionhandler under Other SDKs)    [Myexceptionhandler Setdefaulthandler];    #else        #endif    [Myfilelogger Sharedmanager];

This can be implemented regardless of which page out of the exception can be recorded, because the instance is relatively small, if the source code can leave the mailbox unified send;

iOS exception logging and presentation features

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.