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”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值