NSLog直接写入文件的方法

头文件

//
// Log.h
//
// Created by Chris Wang on 12/16/15.
// Copyright © 2015 CCC. All rights reserved.
//

#import <Foundation/Foundation.h>

#define NSLog(args...) _Log(@"DEBUG ", __FILE__,__LINE__,__PRETTY_FUNCTION__,args);
#define NewLogFile(fileName) (_newFileWithName(fileName));

@interface Log : NSObject

void _Log(NSString *prefix, const char *file, int lineNumber, const char *funcName, NSString *format,...);
void _newFileWithName(NSString *fileName);


@end

实现文件

//
// Log.m
//
// Created by Chris Wang on 12/16/15.
// Copyright © 2015 CCC. All rights reserved.
//

#import "Log.h"

@implementation Log

NSString * newFileName;
NSDateFormatter * formatter;

void _Log(NSString *prefix, const char *file, int lineNumber, const char *funcName, NSString *format,...) {
    va_list ap;
    va_start (ap, format);
    format = [format stringByAppendingString:@"\n"];
    NSString *msg = [[NSString alloc] initWithFormat:[NSString stringWithFormat:@"%@%@",[formatter stringFromDate:[NSDate date]],format] arguments:ap];
    va_end (ap);
    fprintf(stderr,"%s%50s:%3d - %s",[prefix UTF8String], funcName, lineNumber, [msg UTF8String]);
    append(msg);
}

void _newFileWithName(NSString *fileName){
    formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd_HH-mm-ss-SSS";

    newFileName = [NSString stringWithFormat:@"%@_%@.log",[formatter stringFromDate:[NSDate date]],fileName];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS ";
}

void append(NSString *msg){
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    if (!newFileName) {
        formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd_HH-mm-ss-SSS";

        newFileName = [NSString stringWithFormat:@"%@.log",[formatter stringFromDate:[NSDate date]]];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS ";
    }
    NSString *path = [documentsDirectory stringByAppendingPathComponent:newFileName];
    // create if needed
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]){
        fprintf(stderr,"Creating file at %s",[path UTF8String]);
        [[NSData data] writeToFile:path atomically:YES];
    }
    // append
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:path];
    [handle truncateFileAtOffset:[handle seekToEndOfFile]];
    [handle writeData:[msg dataUsingEncoding:NSUTF8StringEncoding]];
    [handle closeFile];
}

@end

最后在pch文件中导入#import “Log.h”

你可能感兴趣的:(写文件,nslog)