iOS自定义NSLog日志

添加俩个文件:WriteLog.h与WriteLog.m

WriteLog.h中:

#define ERR_LOG 1 /* 应用程序无法正常完成操作,比如网络断开,内存分配失败等 */
#define WARN_LOG 2 /* 进入一个异常分支,但并不会引起程序错误 */
#define NOTICE_LOG 3 /* 日常运行提示信息,比如登录、退出日志 */
#define DEBUG_LOG 4 /* 调试信息,打印比较频繁,打印内容较多的日志 */

#define LOGERR(format,...) WriteLog(ERR_LOG,__FUNCTION__,__LINE__,format,##__VA_ARGS__)
#define LOGWARN(format,...) WriteLog(WARN_LOG,__FUNCTION__,__LINE__,format,##__VA_ARGS__)
#define LOGNOTICE(format,...) WriteLog(NOTICE_LOG,__FUNCTION__,__LINE__,format,##__VA_ARGS__)
#define LOGDEBUG(format,...) WriteLog(DEBUG_LOG,__FUNCTION__,__LINE__,format,##__VA_ARGS__)

void WriteLog(int ulErrorLevel, const char *func, int lineNumber, NSString *format, ...);

WriteLog.m中:

#import "WriteLog.h"

void WriteLog(int ulErrorLevel, const char *func, int lineNumber, NSString *format, ...)
{
    va_list args;
    va_start(args, format);
    NSString *string = [[[NSString alloc] initWithFormat:format arguments:args] autorelease];
    va_end(args);

    NSString *strFormat = [NSString stringWithFormat:@"%@%s, %@%i, %@%@",@"Function: ",func,@"Line: ",lineNumber, @"Format: ",string];

    NSString * strModelName = @"WriteLogTest"; //模块名

    NSString *strErrorLevel = [[NSString alloc] init];
    switch (ulErrorLevel) {
        case ERR_LOG:
            strErrorLevel = @"Error";
            break;
        case WARN_LOG:
            strErrorLevel = @"Warning";
            break;
        case NOTICE_LOG:
            strErrorLevel = @"Notice";
            break;
        case DEBUG_LOG:
            strErrorLevel = @"Debug";
            break;
        default:
            break;
    }
    NSLog(@"ModalName: %@, ErrorLevel: %@, %@.",strModelName, strErrorLevel, strFormat);
}

控制台测试输出结果:

2013-03-07 16:37:17.583 WriteLog[419:207] ModalName: WriteLogTest, ErrorLevel: Notice, Function: -[ViewController pressTheButton:], Line: 66, Format: here we press the button.
2013-03-07 16:37:17.585 WriteLog[419:207] ModalName: WriteLogTest, ErrorLevel: Error, Function: -[ViewController pressTheButton:], Line: 67, Format: here we test.
2013-03-07 16:37:17.585 WriteLog[419:207] ModalName: WriteLogTest, ErrorLevel: Warning, Function: -[ViewController pressTheButton:], Line: 68, Format: second test, Yep!.

原文地址:https://www.cnblogs.com/nanoCramer/p/2948365.html