iOS開發中,不少狀況須要使用到log打印,本文主要講解如何將打印寫入文件,而且不影響控制檯的正常打印。git
NSString *documentDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSDateFormatter *dateformat = [[NSDateFormatter alloc]init];
[dateformat setDateFormat:@"yyyy-MM-dd-HH-mm-ss"];
NSString *fileName = [NSString stringWithFormat:@"LOG-%@.txt",[dateformat stringFromDate:[NSDate date]]];
NSString *logFilePath = [documentDirectory stringByAppendingPathComponent:fileName];
// 先刪除已經存在的文件
NSFileManager *defaultManager = [NSFileManager defaultManager];
[defaultManager removeItemAtPath:logFilePath error:nil];
// 將log輸入到文件
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);
freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
複製代碼
這種寫法雖然能夠將打印攔截寫入文件,可是控制檯就沒有了打印,不方便調試。github
考慮到開發總須要查看控制檯打印,實際應用中須要寫入多個文件等狀況,咱們自定義一個打印類來寫日誌文件。具體代碼以下bash
static NSFileHandle *CLLogFileHandle()
{
static NSFileHandle *fileHandle = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *documentsDirectory = [Tools pathDocuments];
NSString *currentFilePath = [documentsDirectory stringByAppendingPathComponent:@"application-0.log"];
NSString *oldestFilePath = [documentsDirectory stringByAppendingPathComponent:@"application-60.log"];
//60文件存在,刪除
if ([fileManager fileExistsAtPath:oldestFilePath]){
[fileManager removeItemAtPath:oldestFilePath error:nil];
}
//遍歷文件,將文件編號日後移動,新增第0的一個文件
for (int i = 60 - 1; i >= 0; i--) {
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"application-%d.log", i]];
NSString *nextFilePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"application-%d.log", i + 1]];
if ([fileManager fileExistsAtPath:filePath])
{
[fileManager moveItemAtPath:filePath toPath:nextFilePath error:nil];
}
}
[fileManager createFileAtPath:currentFilePath contents:nil attributes:nil];
fileHandle = [NSFileHandle fileHandleForWritingAtPath:currentFilePath];
[fileHandle truncateFileAtOffset:0];
});
return fileHandle;
}
void CLLogWithFile(NSString *format, ...) {
va_list L;
va_start(L, format);
NSString *message = [[NSString alloc] initWithFormat:format arguments:L];
NSLog(@"%@", message);
// 開啓異步子線程,將打印寫入文件
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSFileHandle *output = CLLogFileHandle();
if (output != nil) {
time_t rawtime;
struct tm timeinfo;
char buffer[64];
time(&rawtime);
localtime_r(&rawtime, &timeinfo);
struct timeval curTime;
gettimeofday(&curTime, NULL);
int milliseconds = curTime.tv_usec / 1000;
strftime(buffer, 64, "%Y-%m-%d %H:%M", &timeinfo);
char fullBuffer[128] = { 0 };
snprintf(fullBuffer, 128, "%s:%2d.%.3d ", buffer, timeinfo.tm_sec, milliseconds);
[output writeData:[[[NSString alloc] initWithCString:fullBuffer encoding:NSASCIIStringEncoding] dataUsingEncoding:NSUTF8StringEncoding]];
[output writeData:[message dataUsingEncoding:NSUTF8StringEncoding]];
static NSData *returnData = nil;
if (returnData == nil)
returnData = [@"\n" dataUsingEncoding:NSUTF8StringEncoding];
[output writeData:returnData];
}
});
va_end(L);
}
複製代碼
以上代碼主要自定義了打印,而且本身管理了日誌文件個數,不影響正常控制檯的打印。只是這些,可能還不夠,好比咱們還想把當前代碼所在的類文件,方法名稱,行號等也都記錄到文件中,又該怎麼辦呢?咱們能夠使用宏定義,這樣就能夠記錄到這些信息了。app
以上是自定義記錄打印日誌,但願可以給你們幫助,demo地址--->>CLDemo異步