-
Notifications
You must be signed in to change notification settings - Fork 3
/
LCLLogFile.m
925 lines (767 loc) · 29.4 KB
/
LCLLogFile.m
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
//
//
// LCLLogFile.m
//
//
// Copyright (c) 2008-2013 Arne Harren <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "LCLLogFile.h"
#include <unistd.h>
#include <mach/mach_init.h>
#include <sys/time.h>
#include <sys/stat.h>
//
// Configuration checks.
//
#ifndef LCLLogFile
#error 'LCLLogFile' must be defined in LCLLogFileConfig.h
#endif
#ifndef _LCLLogFile_LogFilePath
#error '_LCLLogFile_LogFilePath' must be defined in LCLLogFileConfig.h
#endif
#ifndef _LCLLogFile_AppendToExistingLogFile
#error '_LCLLogFile_AppendToExistingLogFile' must be defined in LCLLogFileConfig.h
#endif
#ifndef _LCLLogFile_MaxLogFileSizeInBytes
#error '_LCLLogFile_MaxLogFileSizeInBytes' must be defined in LCLLogFileConfig.h
#endif
#ifndef _LCLLogFile_MirrorMessagesToStdErr
#error '_LCLLogFile_MirrorMessagesToStdErr' must be defined in LCLLogFileConfig.h
#endif
#ifndef _LCLLogFile_EscapeLineFeeds
#error '_LCLLogFile_EscapeLineFeeds' must be defined in LCLLogFileConfig.h
#endif
#ifndef _LCLLogFile_MaxMessageSizeInCharacters
#error '_LCLLogFile_MaxMessageSizeInCharacters' must be defined in LCLLogFileConfig.h
#endif
#ifndef _LCLLogFile_ShowFileNames
#error '_LCLLogFile_ShowFileNames' must be defined in LCLLogFileConfig.h
#endif
#ifndef _LCLLogFile_ShowLineNumbers
#error '_LCLLogFile_ShowLineNumbers' must be defined in LCLLogFileConfig.h
#endif
#ifndef _LCLLogFile_ShowFunctionNames
#error '_LCLLogFile_ShowFunctionNames' must be defined in LCLLogFileConfig.h
#endif
//
// Fields.
//
// A lock which is held when the log file is used, opened, etc.
static NSRecursiveLock *_LCLLogFile_lock = nil;
// A handle to the current log file, if opened.
static volatile FILE *_LCLLogFile_fileHandle = NULL;
// YES, if logging is active.
static volatile BOOL _LCLLogFile_isActive = NO;
// YES, if log messages should be appended to an existing log file.
static BOOL _LCLLogFile_appendToExistingLogFile = NO;
// YES, if log messages should be mirrored to stderr.
static BOOL _LCLLogFile_mirrorToStdErr = NO;
// YES, if '\\' and '\n' characters should be escaped in log messages.
static BOOL _LCLLogFile_escapeLineFeeds = NO;
// YES, if the file name should be shown.
static BOOL _LCLLogFile_showFileName = NO;
// YES, if the line number should be shown.
static BOOL _LCLLogFile_showLineNumber = NO;
// YES, if the function name should be shown.
static BOOL _LCLLogFile_showFunctionName = NO;
// Max size of a log message (without prefixes).
static NSUInteger _LCLLogFile_maxMessageSize = 0;
// Max size of log file.
static size_t _LCLLogFile_fileSizeMax = 0;
// Current size of log file.
static size_t _LCLLogFile_fileSize = 0;
// Paths of log files.
static NSString *_LCLLogFile_filePath = nil;
static char *_LCLLogFile_filePath_c = NULL;
static NSString *_LCLLogFile_filePath0 = nil;
static char *_LCLLogFile_filePath0_c = NULL;
// The process id.
static pid_t _LCLLogFile_processId = 0;
// The log level headers we use.
static const char * const _LCLLogFile_levelHeader[] = {
"-",
"C",
"E",
"W",
"I",
"D",
"T"
};
// __has_feature for non-clang compilers
#if !defined(__has_feature)
#define __has_feature(_feature) 0
#endif
// ARC defines for non-ARC builds
#if !__has_feature(objc_arc)
#ifndef __bridge
#define __bridge
#endif
#endif
// ARC/non-ARC autorelease pool
#if __has_feature(objc_arc)
#define _LCLLogFile_autoreleasepool_begin \
@autoreleasepool {
#define _LCLLogFile_autoreleasepool_end \
}
#else
#define _LCLLogFile_autoreleasepool_begin \
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
#define _LCLLogFile_autoreleasepool_end \
[pool release];
#endif
#if __has_feature(objc_arc)
#define _LCLLogFile_var_release(_var) \
if (_var != nil) { \
_var = nil; \
}
#else
#define _LCLLogFile_var_release(_var) \
if (_var != nil) { \
[_var release]; \
_var = nil; \
}
#endif
#define _LCLLogFile_var_free(_var) \
if (_var != NULL) { \
free(_var); \
_var = NULL; \
} \
@implementation LCLLogFile
//
// File path.
//
static void _LCLLogFile_setLogFilePath(NSString *path) {
// release old path
_LCLLogFile_var_release(_LCLLogFile_filePath);
_LCLLogFile_var_free(_LCLLogFile_filePath_c);
// release old backup path
_LCLLogFile_var_release(_LCLLogFile_filePath0);
_LCLLogFile_var_free(_LCLLogFile_filePath0_c);
if (path != nil) {
// standardize the given path
path = [path stringByStandardizingPath];
// create parent paths
NSString *parentpath = [path stringByDeletingLastPathComponent];
[[NSFileManager defaultManager] createDirectoryAtPath:parentpath
withIntermediateDirectories:YES
attributes:nil
error:NULL];
// create the path of the backup file
NSString *path0 = [path stringByAppendingString:@".0"];
// create the paths' file system representations
CFIndex path_c_max_len = CFStringGetMaximumSizeOfFileSystemRepresentation((__bridge CFStringRef)path);
CFIndex path0_c_max_len = CFStringGetMaximumSizeOfFileSystemRepresentation((__bridge CFStringRef)path0);
char *path_c = malloc(path_c_max_len);
char *path0_c = malloc(path0_c_max_len);
if (path_c != NULL && path0_c != NULL) {
Boolean path_fsr_created = CFStringGetFileSystemRepresentation((__bridge CFStringRef)path, path_c, path_c_max_len);
Boolean path0_fsr_created = CFStringGetFileSystemRepresentation((__bridge CFStringRef)path0, path0_c, path0_c_max_len);
// create local copies of the paths
if (path_fsr_created && path0_fsr_created) {
_LCLLogFile_filePath = [path copy];
_LCLLogFile_filePath_c = strdup(path_c);
_LCLLogFile_filePath0 = [path0 copy];
_LCLLogFile_filePath0_c = strdup(path0_c);
}
}
_LCLLogFile_var_free(path_c);
_LCLLogFile_var_free(path0_c);
}
// creation of paths failed? clean up and fall back to stderr
if (_LCLLogFile_filePath_c == NULL || _LCLLogFile_filePath0_c == NULL) {
NSLog(@"error: invalid log file path '%@'", path);
// fall back to stderr
_LCLLogFile_mirrorToStdErr = YES;
// release path
_LCLLogFile_var_release(_LCLLogFile_filePath);
_LCLLogFile_var_free(_LCLLogFile_filePath_c);
// release backup path
_LCLLogFile_var_release(_LCLLogFile_filePath0);
_LCLLogFile_var_free(_LCLLogFile_filePath0_c);
}
}
//
// Initialization.
//
// No instances, please.
+(id)alloc {
[LCLLogFile doesNotRecognizeSelector:_cmd];
return nil;
}
// Initializes the class.
+ (void)initialize {
// perform initialization only once
if (self != [LCLLogFile class])
return;
_LCLLogFile_autoreleasepool_begin
// create the lock
_LCLLogFile_lock = [[NSRecursiveLock alloc] init];
// get the process id
_LCLLogFile_processId = getpid();
// get the max file size, at least 4k
_LCLLogFile_fileSizeMax = (_LCLLogFile_MaxLogFileSizeInBytes);
if (_LCLLogFile_fileSizeMax < 4 * 1024) {
_LCLLogFile_fileSizeMax = 4 * 1024;
}
// get whether we should append to an existing log file
_LCLLogFile_appendToExistingLogFile = (_LCLLogFile_AppendToExistingLogFile);
// get whether we should mirror log messages to stderr
_LCLLogFile_mirrorToStdErr = (_LCLLogFile_MirrorMessagesToStdErr);
// get whether we should escape '\\' and '\n' characters in log messages
_LCLLogFile_escapeLineFeeds = (_LCLLogFile_EscapeLineFeeds);
// get max size of a log message
_LCLLogFile_maxMessageSize = (_LCLLogFile_MaxMessageSizeInCharacters);
// get whether we should show file names
_LCLLogFile_showFileName = (_LCLLogFile_ShowFileNames);
// get whether we should show line numbers
_LCLLogFile_showLineNumber = (_LCLLogFile_ShowLineNumbers);
// get whether we should show function names
_LCLLogFile_showFunctionName = (_LCLLogFile_ShowFunctionNames);
// get the full path of the log file
NSString *path = (_LCLLogFile_LogFilePath);
// create log file paths
_LCLLogFile_filePath = nil;
_LCLLogFile_filePath_c = NULL;
_LCLLogFile_filePath0 = nil;
_LCLLogFile_filePath0_c = NULL;
_LCLLogFile_setLogFilePath(path);
// log file size is zero
_LCLLogFile_fileSize = 0;
_LCLLogFile_autoreleasepool_end
}
//
// Logging methods.
//
// Creates the log message prefix.
static NSString *_LCLLogFile_prefix(const char *identifier_c, uint32_t level,
const char *path_c, uint32_t line,
const char *function_c) {
// get settings
const int show_file = _LCLLogFile_showFileName;
const int show_line = _LCLLogFile_showLineNumber;
const int show_function = _LCLLogFile_showFunctionName;
// get file name from path
const char *file_c = NULL;
if (show_file) {
file_c = path_c != NULL ? strrchr(path_c, '/') : NULL;
file_c = (file_c != NULL) ? (file_c + 1) : (path_c);
}
// get line
char line_c[11];
if (show_line) {
snprintf(line_c, sizeof(line_c), "%u", line);
line_c[sizeof(line_c) - 1] = '\0';
}
// get the level header
char level_ca[11];
const char *level_c;
if (level < sizeof(_LCLLogFile_levelHeader)/sizeof(const char *)) {
// a known level, e.g. E, W, I
level_c = _LCLLogFile_levelHeader[level];
} else {
// unknown level, use the level number
snprintf(level_ca, sizeof(level_ca), "%u", level);
level_c = level_ca;
}
// create prefix
NSString *prefix = [NSString stringWithFormat:@" %u:%x %s %s%s%s%s%s%s%s ",
/* */
/* %u */ _LCLLogFile_processId,
/* %x */ mach_thread_self(),
/* */
/* %s */ level_c,
/* */
/* %s */ identifier_c,
/* %s */ show_file ? ":" : "",
/* %s */ show_file ? file_c : "",
/* %s */ show_line ? ":" : "",
/* %s */ show_line ? line_c : "",
/* %s */ show_function ? ":" : "",
/* %s */ show_function ? function_c : ""
/* */
];
return prefix;
}
// Writes the given log message to the log file (internal).
static void _LCLLogFile_log(const char *identifier_c, uint32_t level,
const char *path_c, uint32_t line,
const char *function_c,
NSString *message) {
_LCLLogFile_autoreleasepool_begin
// create the prefix
NSString *prefix = _LCLLogFile_prefix(identifier_c, level, path_c, line, function_c);
// restrict size of log message
if (_LCLLogFile_maxMessageSize != 0) {
NSUInteger message_len = [message length];
if (message_len > _LCLLogFile_maxMessageSize) {
message = [message substringToIndex:_LCLLogFile_maxMessageSize];
}
}
// escape '\\' and '\n' characters
if (_LCLLogFile_escapeLineFeeds) {
NSMutableString *emessage = [[NSMutableString alloc] initWithCapacity:[message length] * 2];
# if !__has_feature(objc_arc)
[emessage autorelease];
# endif
[emessage appendString:message];
# ifndef _LCL_NO_IGNORE_WARNINGS
# ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunknown-pragmas"
# pragma clang diagnostic ignored "-Wassign-enum"
# endif
# endif
[emessage replaceOccurrencesOfString:@"\\" withString:@"\\\\" options:0 range:NSMakeRange(0, [emessage length])];
[emessage replaceOccurrencesOfString:@"\n" withString:@"\\n" options:0 range:NSMakeRange(0, [emessage length])];
# ifndef _LCL_NO_IGNORE_WARNINGS
# ifdef __clang__
# pragma clang diagnostic pop
# endif
# endif
message = emessage;
}
// create C strings
const char *prefix_c = [prefix UTF8String];
const char *message_c = [message UTF8String];
// get size of log entry
char time_c[24];
const int backslash_n_len = 1;
size_t entry_len = sizeof(time_c) + strlen(prefix_c) + strlen(message_c) + backslash_n_len;
// under lock protection ...
[_LCLLogFile_lock lock];
{
FILE *filehandle = (FILE *)_LCLLogFile_fileHandle;
// rotate the log file if required
if (filehandle) {
if (_LCLLogFile_fileSize + entry_len > _LCLLogFile_fileSizeMax) {
[LCLLogFile rotate];
[LCLLogFile open];
filehandle = (FILE *)_LCLLogFile_fileHandle;
}
}
// get current time
struct timeval now;
struct tm now_tm;
gettimeofday(&now, NULL);
localtime_r(&now.tv_sec, &now_tm);
snprintf(time_c, sizeof(time_c), "%04d-%02d-%02d %02d:%02d:%02d.%03d",
now_tm.tm_year + 1900,
now_tm.tm_mon + 1,
now_tm.tm_mday,
now_tm.tm_hour,
now_tm.tm_min,
now_tm.tm_sec,
now.tv_usec / 1000);
// write the log message
if (filehandle) {
// increase file size
_LCLLogFile_fileSize += entry_len;
// write current time and log message
fprintf(filehandle, "%s%s%s\n", time_c, prefix_c, message_c);
// flush the file
fflush(filehandle);
}
// mirror to stderr?
if (_LCLLogFile_mirrorToStdErr) {
# ifndef __LCLLogFile_stderr
# define __LCLLogFile_stderr stderr
# endif
fprintf(__LCLLogFile_stderr, "%s%s%s\n", time_c, prefix_c, message_c);
}
}
// ... done
[_LCLLogFile_lock unlock];
_LCLLogFile_autoreleasepool_end
}
// Writes the given log message to the log file (message).
+ (void)logWithIdentifier:(const char *)identifier level:(uint32_t)level
path:(const char *)path line:(uint32_t)line
function:(const char *)function
message:(NSString *)message {
// open the log file
if (!_LCLLogFile_isActive) {
[LCLLogFile open];
}
// write log message if the log file is opened or mirroring is enabled
if (_LCLLogFile_fileHandle || _LCLLogFile_mirrorToStdErr) {
// write log message
_LCLLogFile_log(identifier, level, path, line, function, message);
}
}
// Writes the given log message to the log file (format and va_list var args).
+ (void)logWithIdentifier:(const char *)identifier level:(uint32_t)level
path:(const char *)path line:(uint32_t)line
function:(const char *)function
format:(NSString *)format args:(va_list)args {
// open the log file
if (!_LCLLogFile_isActive) {
[LCLLogFile open];
}
// write log message if the log file is opened or mirroring is enabled
if (_LCLLogFile_fileHandle || _LCLLogFile_mirrorToStdErr) {
// create log message
# ifndef _LCL_NO_IGNORE_WARNINGS
# ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunknown-pragmas"
# pragma clang diagnostic ignored "-Wformat-nonliteral"
# endif
# endif
NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
# ifndef _LCL_NO_IGNORE_WARNINGS
# ifdef __clang__
# pragma clang diagnostic pop
# endif
# endif
// write log message
_LCLLogFile_log(identifier, level, path, line, function, message);
// release local objects
# if !__has_feature(objc_arc)
[message release];
# endif
}
}
// Writes the given log message to the log file (format and ... var args).
+ (void)logWithIdentifier:(const char *)identifier level:(uint32_t)level
path:(const char *)path line:(uint32_t)line
function:(const char *)function
format:(NSString *)format, ... {
// open the log file
if (!_LCLLogFile_isActive) {
[LCLLogFile open];
}
// write log message if the log file is opened or mirroring is enabled
if (_LCLLogFile_fileHandle || _LCLLogFile_mirrorToStdErr) {
// create log message
va_list args;
va_start(args, format);
NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
va_end(args);
// write log message
_LCLLogFile_log(identifier, level, path, line, function, message);
// release local objects
# if !__has_feature(objc_arc)
[message release];
# endif
}
}
//
// Configuration.
//
// Returns the path of the log file.
+ (NSString *)path {
return _LCLLogFile_filePath;
}
// Returns the path of the backup log file.
+ (NSString *)path0 {
return _LCLLogFile_filePath0;
}
// Sets the path of the log file.
+ (void)setPath:(NSString *)path {
[_LCLLogFile_lock lock];
{
_LCLLogFile_autoreleasepool_begin
[LCLLogFile reset];
_LCLLogFile_setLogFilePath(path);
_LCLLogFile_autoreleasepool_end
}
[_LCLLogFile_lock unlock];
}
// Returns/sets whether log messages get appended to an existing log file on startup.
+ (BOOL)appendsToExistingLogFile {
return _LCLLogFile_appendToExistingLogFile;
}
+ (void)setAppendsToExistingLogFile:(BOOL)value {
[_LCLLogFile_lock lock];
{
_LCLLogFile_appendToExistingLogFile = value;
}
[_LCLLogFile_lock unlock];
}
// Returns/sets the maximum size of the log file (as defined by
// _LCLLogFile_MaxLogFileSizeInBytes).
+ (size_t)maxSize {
return _LCLLogFile_fileSizeMax;
}
+ (void)setMaxSize:(size_t)value {
[_LCLLogFile_lock lock];
{
_LCLLogFile_fileSizeMax = value;
if (_LCLLogFile_fileSizeMax < 4 * 1024) {
_LCLLogFile_fileSizeMax = 4 * 1024;
}
}
[_LCLLogFile_lock unlock];
}
// Returns/sets whether log messages are mirrored to stderr.
+ (BOOL)mirrorsToStdErr {
return _LCLLogFile_mirrorToStdErr;
}
+ (void)setMirrorsToStdErr:(BOOL)value {
[_LCLLogFile_lock lock];
{
_LCLLogFile_mirrorToStdErr = value;
}
[_LCLLogFile_lock unlock];
}
// Returns/sets whether ('\\' and) '\n' line feed characters are escaped in
// log messages.
+ (BOOL)escapesLineFeeds {
return _LCLLogFile_escapeLineFeeds;
}
+ (void)setEscapesLineFeeds:(BOOL)value {
[_LCLLogFile_lock lock];
{
_LCLLogFile_escapeLineFeeds = value;
}
[_LCLLogFile_lock unlock];
}
// Returns/sets the maximum size of a log message in characters (without
// prefixes). The value 0 indicates that there is no maximum size for log
// messages.
+ (NSUInteger)maxMessageSize {
return _LCLLogFile_maxMessageSize;
}
+ (void)setMaxMessageSize:(NSUInteger)value {
[_LCLLogFile_lock lock];
{
_LCLLogFile_maxMessageSize = value;
}
[_LCLLogFile_lock unlock];
}
// Returns/sets whether file names are shown.
+ (BOOL)showsFileNames {
return _LCLLogFile_showFileName;
}
+ (void)setShowsFileNames:(BOOL)value {
[_LCLLogFile_lock lock];
{
_LCLLogFile_showFileName = value;
}
[_LCLLogFile_lock unlock];
}
// Returns/sets whether line numbers are shown.
+ (BOOL)showsLineNumbers {
return _LCLLogFile_showLineNumber;
}
+ (void)setShowsLineNumbers:(BOOL)value {
[_LCLLogFile_lock lock];
{
_LCLLogFile_showLineNumber = value;
}
[_LCLLogFile_lock unlock];
}
// Returns/sets whether function names are shown.
+ (BOOL)showsFunctionNames {
return _LCLLogFile_showFunctionName;
}
+ (void)setShowsFunctionNames:(BOOL)value {
[_LCLLogFile_lock lock];
{
_LCLLogFile_showFunctionName = value;
}
[_LCLLogFile_lock unlock];
}
//
// Status information and internals.
//
// Returns the current size of the log file.
+ (size_t)size {
size_t sz = 0;
[_LCLLogFile_lock lock];
{
// get the size
sz = _LCLLogFile_fileSize;
}
[_LCLLogFile_lock unlock];
return sz;
}
// Opens the log file.
+ (void)open {
[_LCLLogFile_lock lock];
{
if (_LCLLogFile_fileHandle == NULL) {
// size of log file is 0
_LCLLogFile_fileSize = 0;
if (_LCLLogFile_isActive || !_LCLLogFile_appendToExistingLogFile) {
// create a new log file
_LCLLogFile_fileHandle = NULL;
if (_LCLLogFile_filePath_c != NULL) {
_LCLLogFile_fileHandle = fopen(_LCLLogFile_filePath_c, "w");
}
} else {
// append to existing log file, get size from file
_LCLLogFile_fileHandle = NULL;
if (_LCLLogFile_filePath_c != NULL) {
_LCLLogFile_fileHandle = fopen(_LCLLogFile_filePath_c, "a");
}
// try to get size of existing log file
struct stat stat_c;
if (_LCLLogFile_filePath_c != NULL && stat(_LCLLogFile_filePath_c, &stat_c) == 0) {
_LCLLogFile_fileSize = (size_t)stat_c.st_size;
}
}
// logging is active
_LCLLogFile_isActive = YES;
}
}
[_LCLLogFile_lock unlock];
}
// Closes the log file.
+ (void)close {
[_LCLLogFile_lock lock];
{
// close the log file
FILE *filehandle = (FILE *)_LCLLogFile_fileHandle;
if (filehandle != NULL) {
fclose(filehandle);
_LCLLogFile_fileHandle = NULL;
}
// log file size is zero
_LCLLogFile_fileSize = 0;
}
[_LCLLogFile_lock unlock];
}
// Resets the log file.
+ (void)reset {
[_LCLLogFile_lock lock];
{
// close the log file
[LCLLogFile close];
// unlink existing log files
if (_LCLLogFile_filePath_c != NULL) {
unlink(_LCLLogFile_filePath_c);
}
if (_LCLLogFile_filePath0_c != NULL) {
unlink(_LCLLogFile_filePath0_c);
}
// logging is not active
_LCLLogFile_isActive = NO;
}
[_LCLLogFile_lock unlock];
}
// Rotates the log file.
+ (void)rotate {
[_LCLLogFile_lock lock];
{
// close the log file
[LCLLogFile close];
// keep a copy of the current log file
if (_LCLLogFile_filePath_c != NULL && _LCLLogFile_filePath0_c != NULL) {
rename(_LCLLogFile_filePath_c, _LCLLogFile_filePath0_c);
}
}
[_LCLLogFile_lock unlock];
}
//
// Methods for creating log file paths.
//
// Returns a default path for a log file which is based on the Info.plist
// files which are associated with this class. The returned path has the form
// ~/Library/Logs/<main>/<this>.log
// where
// <main> is the name (or identifier) of the application's main bundle, and
// <this> is the name (or identifier) of the bundle to which this LCLLogFile
// class belongs.
// This method is a convenience method which calls defaultPathWithPathPrefix
// with the prefix ~/Library/Logs and the given fallback path.
+ (NSString *)defaultPathInHomeLibraryLogsOrPath:(NSString *)path {
return [LCLLogFile defaultPathWithPathPrefix:
[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Logs"]
orPath:path];
}
// Returns a default path for a log file which is based on the Info.plist
// files which are associated with this class. The returned path has the form
// <path>/<main>/<this>.log
// where
// <path> is the given path prefix,
// <main> is the name (or identifier) of the application's main bundle, and
// <this> is the name (or identifier) of the bundle to which this LCLLogFile
// class belongs.
// If the name or identifier cannot be retrieved from the main bundle, the
// returned default path has the form
// <path>/<this>/<this>.<pid>.log
// where
// <pid> is the current process id.
// If the name or identifier cannot be retrieved from the bundle which
// corresponds to this LCLLogFile class, or if the given path prefix <path> is
// nil, the given fallback path is returned.
+ (NSString *)defaultPathWithPathPrefix:(NSString *)pathPrefix
orPath:(NSString *)path {
// get the main bundle and the bundle which corresponds to this class
NSBundle *pathBundle = [NSBundle mainBundle];
NSBundle *fileBundle = [NSBundle bundleForClass:[LCLLogFile class]];
NSString *pathComponent = [LCLLogFile defaultPathComponentFromPathBundle:pathBundle
fileBundle:fileBundle
orPathComponent:nil];
if (pathPrefix != nil && pathComponent != nil) {
return [pathPrefix stringByAppendingPathComponent:pathComponent];
} else {
return path;
}
}
// Returns a default path component for a log file which is based on the given
// bundles' Info.plist files. The returned path has the form
// <path>/<file>.log
// where
// <path> is the name (or identifier) of the given path bundle, and
// <file> is the name (or identifier) of the given file bundle.
// If the name or identifier cannot be retrieved from the path bundle, the
// returned default path has the form
// <file>/<file>.<pid>.log
// where
// <pid> is the current process id.
// If the name or identifier cannot be retrieved from the file bundle, the
// given fallback path component is returned.
+ (NSString *)defaultPathComponentFromPathBundle:(NSBundle *)pathBundle
fileBundle:(NSBundle *)fileBundle
orPathComponent:(NSString *)pathComponent {
NSString *pathName = [LCLLogFile nameOrIdentifierFromBundle:pathBundle
orString:nil];
NSString *fileName = [LCLLogFile nameOrIdentifierFromBundle:fileBundle
orString:nil];
if (pathName != nil && fileName != nil) {
// we have a path name and a file name
return [NSString stringWithFormat:@"%@/%@.log", pathName, fileName];
} else if (pathName == nil && fileName != nil) {
// we don't have a path name, but a file name, use the file name as
// the path name and append the pid to the file name to avoid collisions
return [NSString stringWithFormat:@"%@/%@.%u.log", fileName, fileName, getpid()];
} else {
// no information from the bundles, fail
return pathComponent;
}
}
// Returns the name from the given bundle's Info.plist file. If the name doesn't
// exist, the bundle's identifier is returned. If the identifier doesn't exist,
// the given fallback string is returned.
+ (NSString *)nameOrIdentifierFromBundle:(NSBundle *)bundle
orString:(NSString *)string {
id bundleName = [bundle objectForInfoDictionaryKey:@"CFBundleName"];
if (bundleName != nil && [bundleName isKindOfClass:[NSString class]]) {
return (NSString *)bundleName;
}
NSString *bundleIdentifier = [bundle bundleIdentifier];
if (bundleIdentifier != nil) {
return bundleIdentifier;
}
return string;
}
@end