QNLogUtil.m 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //
  2. // QNLogUtil.m
  3. // QiniuSDK
  4. //
  5. // Created by yangsen on 2020/12/25.
  6. // Copyright © 2020 Qiniu. All rights reserved.
  7. //
  8. #import "QNLogUtil.h"
  9. #if DEBUG
  10. static QNLogLevel _level = QNLogLevelError;
  11. #else
  12. static QNLogLevel _level = QNLogLevelNone;
  13. #endif
  14. static BOOL _enableDate = false;
  15. static BOOL _enableFile = true;
  16. static BOOL _enableFunction = false;
  17. @implementation QNLogUtil
  18. + (void)setLogLevel:(QNLogLevel)level {
  19. _level = level < 0 ? 0 : level;
  20. }
  21. + (void)enableLogDate:(BOOL)enable {
  22. _enableDate = enable;
  23. }
  24. + (void)enableLogFile:(BOOL)enable {
  25. _enableFile = enable;
  26. }
  27. + (void)enableLogFunction:(BOOL)enable {
  28. _enableFunction = enable;
  29. }
  30. + (void)log:(QNLogLevel)level
  31. file:(const char *)file
  32. function:(const char *)function
  33. line:(NSUInteger)line
  34. format:(NSString *)format, ... {
  35. if (!format || level > _level) {
  36. return;
  37. }
  38. va_list args;
  39. va_start(args, format);
  40. NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
  41. va_end(args);
  42. NSString *fileName = @"";
  43. if (_enableFile) {
  44. fileName = [NSString stringWithFormat:@"%s", file];
  45. if ([fileName containsString:@"/"]) {
  46. fileName = [fileName componentsSeparatedByString:@"/"].lastObject;
  47. }
  48. }
  49. NSString *functionName = @"";
  50. if (_enableFunction) {
  51. functionName = [NSString stringWithFormat:@"->%s", function];
  52. }
  53. NSString *lineNumber = [NSString stringWithFormat:@"->%ld", line];
  54. NSString *date = @"";
  55. if (_enableDate) {
  56. date = [NSString stringWithFormat:@"%@", [NSDate date]];
  57. if ([date length] > 20) {
  58. date = [date substringToIndex:19];
  59. }
  60. }
  61. NSThread *thread = [NSThread currentThread];
  62. NSString *levelString = @[@"N", @"E", @"W", @"I", @"D", @"V"][level%6];
  63. message = [NSString stringWithFormat:@"%@[%@] %@ %@%@%@ %@", date, levelString, thread, fileName, functionName, lineNumber, message];
  64. NSLog(@"%@", message);
  65. }
  66. @end