summaryrefslogtreecommitdiff
path: root/SmartDeviceLink/SDLLogManager.m
blob: ae0fa317ff211ba390cb27c46158a8db5e748da8 (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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
//
//  SDLLogManager.m
//  SmartDeviceLink-iOS
//
//  Created by Joel Fischer on 2/27/17.
//  Copyright © 2017 smartdevicelink. All rights reserved.
//

#import "SDLLogManager.h"

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


NS_ASSUME_NONNULL_BEGIN

@interface SDLLogManager ()

@property (copy, nonatomic, readwrite) NSSet<SDLLogFileModule *> *modules;
@property (copy, nonatomic, readwrite) NSSet<id<SDLLogTarget>> *targets;
@property (copy, nonatomic, readwrite) NSSet<SDLLogFilter *> *filters;

@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 (assign, nonatomic, readwrite, getter=areAssertionsDisabled) BOOL disableAssertions;

@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;
    }

    _modules = [NSSet set];
    _targets = [NSSet set];
    _filters = [NSSet set];

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

    return self;
}


#pragma mark - Configuration

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

- (void)setConfiguration:(SDLLogConfiguration *)configuration {
    self.modules = configuration.modules;
    self.filters = configuration.filters;
    self.formatType = configuration.formatType;
    self.asynchronous = configuration.isAsynchronous;
    self.errorsAsynchronous = configuration.areErrorsAsynchronous;
    self.disableAssertions = configuration.areAssertionsDisabled;
    self.globalLogLevel = configuration.globalLogLevel;

    // Start the loggers
    NSMutableSet<id<SDLLogTarget>> *startedLoggers = [NSMutableSet set];
    for (id<SDLLogTarget> target in configuration.targets) {
        // 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.targets = [startedLoggers copy];
}


#pragma mark - Performing Logging

+ (void)logBytes:(NSData *)data direction:(SDLLogBytesDirection)direction timestamp:(NSDate *)timestamp file:(NSString *)file functionName:(NSString *)functionName line:(NSInteger)line queue:(NSString *)queueLabel {
    [[self sharedManager] logBytes:data direction:direction timestamp:timestamp file:file functionName:functionName line:line queue:queueLabel];
}

+ (void)logAssertWithTimestamp:(NSDate *)timestamp 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] logAssertWithTimestamp:timestamp file:file functionName:functionName line:line queue:queueLabel formatMessage:@"%@", format];
}

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

+ (void)logWithLevel:(SDLLogLevel)level timestamp:(NSDate *)timestamp 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 timestamp:timestamp file:file functionName:functionName line:line queue:queueLabel message:format];
}

- (void)logBytes:(NSData *)data direction:(SDLLogBytesDirection)direction timestamp:(NSDate *)timestamp file:(NSString *)file functionName:(NSString *)functionName line:(NSInteger)line queue:(NSString *)queueLabel {
    // This only works on Verbose logging
    if ([self sdl_logLevelForFile:file] < SDLLogLevelVerbose) { return; }

    NSString *message = [NSString stringWithFormat:@"%@(%lu bytes): %@", [self sdl_logStringForDirection:direction], (unsigned long)data.length, [SDLHexUtility getHexString:data]];
    [self logWithLevel:SDLLogLevelVerbose timestamp:timestamp file:file functionName:functionName line:line queue:queueLabel message:message];
}

- (void)logAssertWithTimestamp:(NSDate *)timestamp 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:SDLLogLevelError timestamp:timestamp file:file functionName:functionName line:line queue:queueLabel message:format];

    NSAssert(self.areAssertionsDisabled, @"SDL ASSERTION: %@. To disable these assertions, alter your `SDLLogConfiguration` and set `disableAssertions` to `YES`", format);
}

- (void)logWithLevel:(SDLLogLevel)level timestamp:(NSDate *)timestamp 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 timestamp:timestamp file:file functionName:functionName line:line queue:queueLabel message:format];
}

- (void)logWithLevel:(SDLLogLevel)level timestamp:(NSDate *)timestamp file:(NSString *)file functionName:(NSString *)functionName line:(NSInteger)line queue:(NSString *)queueLabel message:(NSString *)message {
    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 {
    [self sdl_log:log];
}

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

    for (SDLLogFilter *filter in self.filters) {
        if (!filter.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.targets) {
        [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";
    }
}

- (NSString *)sdl_logStringForDirection:(SDLLogBytesDirection)direction {
    switch (direction) {
        case SDLLogBytesDirectionReceive:
            return @"RX";
        case SDLLogBytesDirectionTransmit:
            return @"TX";
    }
}


#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.modules) {
        if ([module containsFile:fileName]) { return module; }
    }

    return nil;
}


#pragma mark - Class property getters

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

    return _dateFormatter;
}

+ (dispatch_queue_t)logQueue {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (@available(iOS 10.0, *)) {
            _logQueue = dispatch_queue_create_with_target("com.sdl.log", DISPATCH_QUEUE_SERIAL, [SDLGlobals sharedGlobals].sdlProcessingQueue);
        } else {
            _logQueue = [SDLGlobals sharedGlobals].sdlProcessingQueue;
        }
    });

    return _logQueue;
}

@end

NS_ASSUME_NONNULL_END