summaryrefslogtreecommitdiff
path: root/SmartDeviceLink/SDLLogManager.m
blob: 8b69fbd75bb4dc2b2e2b5c98a93c77c11bf57e44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
//
//  SDLLogManager.m
//  SmartDeviceLink-iOS
//
//  Created by Joel Fischer on 2/27/17.
//  Copyright © 2017 smartdevicelink. All rights reserved.
//

#import "SDLLogManager.h"

#import "SDLLogConfiguration.h"
#import "SDLLogFileModule.h"
#import "SDLLogModel.h"


NS_ASSUME_NONNULL_BEGIN

@interface SDLLogManager ()

@property (copy, nonatomic, readwrite) NSSet<SDLLogFileModule *> *logModules;
@property (copy, nonatomic, readwrite) NSSet<id<SDLLogTarget>> *logTargets;
@property (copy, nonatomic, readwrite) NSSet<SDLLogFilterBlock> *logFilters;

@property (assign, nonatomic, readwrite) SDLLogLevel globalLogLevel;
@property (assign, nonatomic, readwrite) SDLLogFormatType formatType;

@property (assign, nonatomic, readwrite, getter=isAsynchronous) BOOL asynchronous;
@property (assign, nonatomic, readwrite, getter=areErrorsAsynchronous) BOOL errorsAsynchronous;

@property (class, strong, nonatomic, readonly) NSDateFormatter *dateFormatter;
@property (class, assign, nonatomic, readonly) dispatch_queue_t logQueue;

@end

@implementation SDLLogManager

static NSDateFormatter *_dateFormatter = nil;
static dispatch_queue_t _logQueue = NULL;

+ (SDLLogManager *)sharedManager {
    static SDLLogManager *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[SDLLogManager alloc] init];
    });

    return sharedManager;
}

- (instancetype)init {
    self = [super init];
    if (!self) {
        return nil;
    }

    _logModules = [NSSet set];
    _logTargets = [NSSet set];
    _logFilters = [NSSet set];

    _asynchronous = YES;
    _errorsAsynchronous = NO;
    _globalLogLevel = SDLLogLevelError;
    _formatType = SDLLogFormatTypeDefault;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _dateFormatter = [[NSDateFormatter alloc] init];
        _dateFormatter.dateFormat = @"HH:mm:ss:SSS";

        _logQueue = dispatch_queue_create("com.sdl.log", DISPATCH_QUEUE_SERIAL);
    });

    return self;
}


#pragma mark - Configuration

+ (void)setConfiguration:(SDLLogConfiguration *)configuration {
    [[self sharedManager] setConfiguration:configuration];
}

- (void)setConfiguration:(SDLLogConfiguration *)configuration {
    self.logModules = configuration.logModules;
    self.logFilters = configuration.logFilters;
    self.formatType = configuration.formatType;
    self.asynchronous = configuration.isAsynchronous;
    self.errorsAsynchronous = configuration.areErrorsAsynchronous;
    self.globalLogLevel = configuration.globalLogLevel;

    // Start the loggers
    NSMutableSet<id<SDLLogTarget>> *startedLoggers = [NSMutableSet set];
    for (id<SDLLogTarget> target in configuration.logTargets) {
        // If the logger fails setup, discard it, otherwise, keep it
        if ([target setupLogger]) {
            [startedLoggers addObject:target];
        } else {
            // Because we haven't set up loggers yet, this is necessary
            NSLog(@"(SDL) Warning: Log target failed setup: %@", NSStringFromClass(target.class));
        }
    }
    self.logTargets = [startedLoggers copy];
}


#pragma mark - Performing Logging

+ (void)logWithLevel:(SDLLogLevel)level file:(NSString *)file functionName:(NSString *)functionName line:(NSInteger)line queue:(NSString *)queueLabel message:(NSString *)message {
    [[self sharedManager] logWithLevel:level file:file functionName:functionName line:line queue:queueLabel message:message];
}

+ (void)logWithLevel:(SDLLogLevel)level file:(NSString *)file functionName:(NSString *)functionName line:(NSInteger)line queue:(NSString *)queueLabel formatMessage:(NSString *)message, ... {
    va_list args;
    va_start(args, message);
    NSString *format = [[NSString alloc] initWithFormat:message arguments:args];
    va_end(args);

    [[self sharedManager] logWithLevel:level file:file functionName:functionName line:line queue:queueLabel message:format];
}

- (void)logWithLevel:(SDLLogLevel)level file:(NSString *)file functionName:(NSString *)functionName line:(NSInteger)line queue:(NSString *)queueLabel formatMessage:(NSString *)message, ... {
    va_list args;
    va_start(args, message);
    NSString *format = [[NSString alloc] initWithFormat:message arguments:args];
    va_end(args);

    [self logWithLevel:level file:file functionName:functionName line:line queue:queueLabel message:format];
}

- (void)logWithLevel:(SDLLogLevel)level file:(NSString *)file functionName:(NSString *)functionName line:(NSInteger)line queue:(NSString *)queueLabel message:(NSString *)message {
    NSDate *timestamp = [NSDate date];
    NSString *moduleName = [self sdl_moduleForFile:file] ? [self sdl_moduleForFile:file].name : @"";

    SDLLogModel *log = [[SDLLogModel alloc] initWithMessage:message
                                                  timestamp:timestamp
                                                      level:level
                                                   fileName:file
                                                 moduleName:moduleName
                                               functionName:functionName
                                                       line:line
                                                 queueLabel:queueLabel];
    [self sdl_queueLog:log];
}

- (void)sdl_queueLog:(SDLLogModel *)log {
    if (log.level == SDLLogLevelError) {
        if (self.areErrorsAsynchronous) {
            [self sdl_asyncLog:log];
        } else {
            [self sdl_syncLog:log];
        }
    } else {
        if (self.isAsynchronous) {
            [self sdl_asyncLog:log];
        } else {
            [self sdl_syncLog:log];
        }
    }
}

- (void)sdl_asyncLog:(SDLLogModel *)log {
    dispatch_async(self.class.logQueue, ^{
        [self sdl_log:log];
    });
}

- (void)sdl_syncLog:(SDLLogModel *)log {
    dispatch_sync(self.class.logQueue, ^{
        [self sdl_log:log];
    });
}

- (void)sdl_log:(SDLLogModel *)log {
    if ([self sdl_logLevelForFile:log.fileName] < log.level) { return; }

    for (SDLLogFilterBlock filter in self.logFilters) {
        if (!filter(log)) { return; }
    }

    NSString *formattedLog = nil;
    switch (self.formatType) {
        case SDLLogFormatTypeSimple:
            formattedLog = [self sdl_simpleFormatLog:log];
            break;
        case SDLLogFormatTypeDefault:
            formattedLog = [self sdl_defaultFormatLog:log];
            break;
        case SDLLogFormatTypeDetailed:
            formattedLog = [self sdl_detailedFormatLog:log];
            break;
    }

    for (id<SDLLogTarget> target in self.logTargets) {
        [target logWithLog:log formattedLog:formattedLog];
    }
}


#pragma mark - Log formatting

- (NSString *)sdl_simpleFormatLog:(SDLLogModel *)log {
    return [self sdl_formatLog:log showDate:YES showLogLevelCharacter:YES showLogLevelName:NO showQueueName:NO showModuleName:YES showFileName:NO showFunctionName:NO showLine:NO];
}

- (NSString *)sdl_defaultFormatLog:(SDLLogModel *)log {
    return [self sdl_formatLog:log showDate:YES showLogLevelCharacter:YES showLogLevelName:NO showQueueName:NO showModuleName:YES showFileName:YES showFunctionName:NO showLine:YES];
}

- (NSString *)sdl_detailedFormatLog:(SDLLogModel *)log {
    return [self sdl_formatLog:log showDate:YES showLogLevelCharacter:YES showLogLevelName:YES showQueueName:YES showModuleName:YES showFileName:YES showFunctionName:YES showLine:YES];
}

- (NSString *)sdl_formatLog:(SDLLogModel *)log showDate:(BOOL)date showLogLevelCharacter:(BOOL)logChar showLogLevelName:(BOOL)logName showQueueName:(BOOL)queueName showModuleName:(BOOL)moduleName showFileName:(BOOL)fileName showFunctionName:(BOOL)functionName showLine:(BOOL)line {
    NSMutableString *logString = [NSMutableString string];

    if (date) {
        [logString appendFormat:@"%@ ", [self.class.dateFormatter stringFromDate:log.timestamp]];
    }
    if (logChar) {
        [logString appendFormat:@"%@ ", [self sdl_logCharacterForLevel:log.level]];
    }
    if (logName) {
        [logString appendFormat:@"%@ ", [self sdl_logNameForLevel:log.level]];
    }
    if (queueName) {
        [logString appendFormat:@"%@ ", log.queueLabel];
    }
    if (moduleName) {
        [logString appendFormat:@"(SDL)%@", log.moduleName];
    }
    if (fileName) {
        [logString appendFormat:@":%@", log.fileName];
    }
    if (functionName) {
        [logString appendFormat:@":%@", log.functionName];
    }
    if (line) {
        [logString appendFormat:@":%ld ", (long)log.line];
    }
    [logString appendFormat:@"- %@\n", log.message];

    return [logString copy];
}

- (NSString *)sdl_logCharacterForLevel:(SDLLogLevel)logLevel {
    switch (logLevel) {
        case SDLLogLevelVerbose: return @"⚪";
        case SDLLogLevelDebug: return @"🔵";
        case SDLLogLevelWarning: return @"🔶";
        case SDLLogLevelError: return @"❌";
        default:
            NSAssert(NO, @"The OFF and DEFAULT log levels are not valid to log with.");
            return @"";
    }
}

- (NSString *)sdl_logNameForLevel:(SDLLogLevel)logLevel {
    switch (logLevel) {
        case SDLLogLevelVerbose: return @"VERBOSE";
        case SDLLogLevelDebug: return @"DEBUG";
        case SDLLogLevelWarning: return @"WARNING";
        case SDLLogLevelError: return @"ERROR";
        default:
            NSAssert(NO, @"The OFF and DEFAULT log levels are not valid to log with.");
            return @"UNKNOWN";
    }
}


#pragma mark - Modules

- (SDLLogLevel)sdl_logLevelForFile:(NSString *)fileName {
    SDLLogFileModule *module = [self sdl_moduleForFile:fileName];
    if (!module) {
        return self.globalLogLevel;
    }

    if ([module containsFile:fileName]) {
        if (module.logLevel == SDLLogLevelDefault) {
            return self.globalLogLevel;
        }
    }

    return module.logLevel;
}

- (nullable SDLLogFileModule *)sdl_moduleForFile:(NSString *)fileName {
    for (SDLLogFileModule *module in self.logModules) {
        if ([module containsFile:fileName]) { return module; }
    }

    return nil;
}


#pragma mark - Class property getters

+ (NSDateFormatter *)dateFormatter {
    return _dateFormatter;
}

+ (dispatch_queue_t)logQueue {
    return _logQueue;
}

@end

NS_ASSUME_NONNULL_END