MST
星途 面试题库

面试题:Objective-C 中如何设计一个简单的日志系统

在Objective-C中,请阐述设计一个基础日志系统的思路,包括如何记录不同级别的日志(如调试、信息、警告、错误),以及如何指定日志输出的位置(如控制台、文件)。同时,请给出关键代码示例。
28.3万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 定义日志级别:通过枚举来定义不同的日志级别,如调试、信息、警告、错误等。
  2. 日志输出位置:创建不同的输出策略,分别处理控制台输出和文件输出。
  3. 统一接口:提供一个统一的日志记录接口,根据不同的日志级别和输出位置进行相应处理。

关键代码示例

  1. 定义日志级别枚举
typedef NS_ENUM(NSInteger, LogLevel) {
    LogLevelDebug,
    LogLevelInfo,
    LogLevelWarning,
    LogLevelError
};
  1. 日志记录接口
@interface Logger : NSObject

+ (void)logMessage:(NSString *)message level:(LogLevel)level toDestination:(NSString *)destination;

@end

@implementation Logger

+ (void)logMessage:(NSString *)message level:(LogLevel)level toDestination:(NSString *)destination {
    NSString *levelString;
    switch (level) {
        case LogLevelDebug:
            levelString = @"DEBUG";
            break;
        case LogLevelInfo:
            levelString = @"INFO";
            break;
        case LogLevelWarning:
            levelString = @"WARN";
            break;
        case LogLevelError:
            levelString = @"ERROR";
            break;
    }
    NSString *logMessage = [NSString stringWithFormat:@"[%@] %@", levelString, message];
    if ([destination isEqualToString:@"console"]) {
        NSLog(@"%@", logMessage);
    } else if ([destination isEqualToString:@"file"]) {
        NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        NSString *logFilePath = [documentsPath stringByAppendingPathComponent:@"log.txt"];
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
        if (!fileHandle) {
            [[NSFileManager defaultManager] createFileAtPath:logFilePath contents:nil attributes:nil];
            fileHandle = [NSFileHandle fileHandleForWritingAtPath:logFilePath];
        }
        [fileHandle seekToEndOfFile];
        [fileHandle writeData:[logMessage dataUsingEncoding:NSUTF8StringEncoding]];
        [fileHandle writeData:[@"\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [fileHandle closeFile];
    }
}

@end
  1. 使用示例
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        [Logger logMessage:@"This is a debug message" level:LogLevelDebug toDestination:@"console"];
        [Logger logMessage:@"This is an info message" level:LogLevelInfo toDestination:@"file"];
    }
    return 0;
}