Timing of controlling nslog output in IOS

  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentDirectory = [paths objectAtIndex:0];
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  [dateFormatter setDateFormat:@"yyyy_MM_dd_HH_mm_ss"];
  NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
  NSString *fileName = [NSString stringWithFormat:@"testLog_%@.log",currentDateStr];
  NSString *logFilePath = [documentDirectory stringByAppendingPathComponent:fileName];
  //Delete the existing file first
  NSFileManager *defaultManager = [NSFileManager defaultManager];
  [defaultManager removeItemAtPath:logFilePath error:nil];
  //Input log to file
  freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);
  freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);

This method mainly calls the freeopen method to write. Stdout and stderr include most of the abnormal output of IOS.

2. Control the log output according to the bool value

Users encounter all kinds of problems when using the app. When they and the test team are not able to locate the reasons, it is the best way to send the log of key points to the users. But how to save part of the log in the process of APP running? Like a switch to control log reading and writing? Through reading mqttlog source code to find inspiration.

First, nslog is replaced by the next macro, and slog is used to output in the project

#define SLOG(fmt, ...) if (reportLoggerIsOpen) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)From the macro definition, we can see that reportloggerisopen is the switch that controls the output of log. For the definition of reportloggerisopen, we first declare this variable in extern in H file, and then implement it in m file.

. h file

#import <Foundation/Foundation.h>

extern BOOL reportLoggerIsOpen;
. m file
BOOL reportLoggerIsOpen = NO;

+ (void)setLogOpen:(BOOL)open {
  reportLoggerIsOpen = open;

Through the setlogopen method, you can control log writing freely. For example, if you need to capture the log of the login module, you can pass in true before login, and pass in false after login, so that only the log of the login module can be retained.