//
// HCLog.h
// Test
//
// Created by on 14-4-21.
// Copyright (c) 2014年 . All rights reserved.
//
#import <Foundation/Foundation.h>
#define HHCLog(formatter,...) [[HCLog shareInstance]write:formatter,##__VA_ARGS__]
@interface HCLog : NSObject
+(HCLog*)shareInstance;
-(BOOL)write:(NSString *)format,...;
@end
//
// HCLog.m
// Test
//
// Created by on 14-4-21.
// Copyright (c) 2014年 . All rights reserved.
//
#import "HCLog.h"
static HCLog *_hclog = nil;
@implementation HCLog
+(HCLog*)shareInstance{
if (_hclog == nil) {
_hclog = [[HCLog alloc]init];
}
return _hclog;
}
-(BOOL)write:(NSString *)format,...
{
@synchronized(self)
{
va_list args;
if (format)
{
va_start(args, format);
NSString *logMsg = [[NSString alloc] initWithFormat:format arguments:args];
NSFileManager * fileManager = [NSFileManager defaultManager];
NSString *dirctory = [NSString stringWithFormat:@"%@/log",NSHomeDirectory()];
NSString *file = [NSString stringWithFormat:@"%@/log/%@.log",NSHomeDirectory(),self.getCurrentTime];
BOOL isDirctory = YES;
if (![fileManager fileExistsAtPath:dirctory isDirectory:&isDirctory]) { //不存在就创建
if(![fileManager createDirectoryAtPath:dirctory withIntermediateDirectories:YES attributes:nil error:nil])
{
NSLog(@"%@ 文件目录创建失败",dirctory);
return NO;
}
}
isDirctory = NO;
if (![fileManager fileExistsAtPath:file isDirectory:&isDirctory]) {
if(![fileManager createFileAtPath:file contents:nil attributes:nil ])
{
NSLog(@"%@ 文件创建失败",file);
return NO;
}
}
[logMsg writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:nil];
va_end(args);
}
return YES;
}
}
-(NSString*)getCurrentTime{
time_t t;
time(&t);
NSDate *date = [NSDate dateWithTimeIntervalSince1970:t];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSString *strDate = [formatter stringFromDate:date];
return strDate;
}
@end
//使用
NSString* str = @"world";
HHCLog("hello %@",str);