Writing in the front

For an APP already online, if there is no own Log system. Once there is a problem online, you will receive all kinds of aite leaders of wechat, all kinds of customer complaints. So a mature Log system of its own is crucial. This article focuses on the real-time log viewing function under the LAN.

Demand analysis

The input

  • Supports file writing and reading
  • Supports setting a single file size
  • You can set the write time of a single file
  • Supports setting the total number of log files
  • Support log file validity time
  • Database writes and reads are supported
  • Support log levels (Off, Error, Debug, Info, Verbose)
  • Supports custom format
  • Console and console.app are supported
  • Log Filtering

The output

  • Support shake log file sharing
  • Supports LAN logs Real-time logs
  • Log files can be uploaded to the server
  • The server can enable or disable logging for a single APP account or deviceID

System architecture

recommendation

CocoaLumberjack supports log output at multiple levels by default and can flexibly expand the log level, log format, and log filtering conditions. Default support for log file size, number of file writes, and so on. Most of the requirements are met.

Function implementation

Add terminal output

[DDLog addLogger:[DDTTYLogger sharedInstance]];
Copy the code

Example Add the Apple System log

[DDLog addLogger:[DDASLLogger sharedInstance]];
Copy the code

Use OS versions macosx(10.4,10.12), ios(2.0,10.0), watchos(2.0,3.0), tvos(9.0,10.0) and replace with the following.

[DDLog addLogger:[DDOSLogger sharedInstance]];
Copy the code

The custom format

Custom Format requires creating a class and following the protocol DDLogFormatter, and then implementing the methods.

@interface LogFormatter : NSObject<DDLogFormatter>

@end
@implementation LogFormatter

- (NSString * _Nullable)formatLogMessage:(nonnull DDLogMessage *)logMessage {
    return [NSString stringWithFormat:@"[%@]:%@ line:%@ ----%@".logMessage->_fileName,logMessage->_function,@(logMessage->_line),logMessage->_message];
}

@end
Copy the code

Written to the file

fileLogger = [[DDFileLogger alloc] init]; fileLogger.maximumFileSize = 1024 * 1; / / 1 KB file maximum size fileLogger. RollingFrequency = 60 * 1; / / 60 Seconds a single file the capital log time fileLogger. LogFileManager. MaximumNumberOfLogFiles = 4; // Maximum number of files [DDLog addLogger:fileLogger];Copy the code

Write to database

Writing to the database requires the implementation of a custom Logger class, and the official Demo FMDBLogger is used in this article

Add SQLiteLogger

sqliteLogger = [[FMDBLogger alloc] initWithLogDirectory:logsDirectory]; sqliteLogger.saveThreshold = 500; / / when the cache reaches the threshold into sqliteLogger. SaveInterval = 60; // 60 seconds sqliteLogger. MaxAge = 60 * 60 * 24 * 7; . / / the biggest save time sqliteLogger deleteInterval = 60 * 5; / / the official explanation says, probably delete is a very time consuming IO operations, so set an interval sqliteLogger. DeleteOnEverySave = NO; [DDLog addLogger:sqliteLogger];Copy the code

Real-time LAN Logs

The general steps are as follows:

  • Real-time transmission of logs is realized based on Websocket
  • In the APP with JS +HTML to achieve a websocket client xxx. HTML file
  • Start webServer in APP and set xxx. HTML to root document
  • Open http://yourIP:port with a browser on any end, as long as the browser supports WebSocket
  • The APP intercepts the log when a Websocket connects to the local Webserver and sends the log to the JS websocket client

The HTML code

<! DOCTYPE html> <html> <head> <meta charset="utf-8">
        <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,shrink-to-fit=no"><meta name="theme-color" content="# 000000">
        <title>Live log</title>
        <script>
            var dpr,rem,docEl=document.documentElement,fontEl=document.createElement("style"),scale=(docEl.clientWidth/375).toFixed(2); DPR = window. DevicePixelRatio | | 1,1.4 < scale && (scale = 1), rem = 12 * scale, docEl. SetAttribute ("data-dpr",dpr),docEl.setAttribute("data-scale",scale),docEl.firstElementChild.appendChild(fontEl),fontEl.innerHTML="html{font-size:"+rem+"px! important; }"
            </script>
    </head>
    <body>
        <a id="openApp"> open the browser review elements, enter the console interface < / a > < script > var url = window. The location, origin. Replace ("http"."ws") +"/livelog";
            var ws = new WebSocket(url);
            ws.onclose = function (event) {
                console.log("ws close:",event.data);
            }
            ws.onerror = function (event) {
                console.log("ws error:",event.data);
            }
            ws.onmessage = function (event) {
                var data = event.data;
                console.log(data);
            }
            ws.onopen = function (event) {console.log("ws opened"); } window.webs = ws; </script> </body> </html>Copy the code

Shake and share

As it involves other business of the project, only ideas are provided.

The log switch displays the configuration of an alert page after being shaken, and once turned on starts logging and writing to a local file. Want in recurring problems or capture the log after shake again choose corresponding log, using UIDocumentInteractionController share the WeChat and airdrop. Shake to share the configuration log switch suitable for informal use, if the online version, can be started by the following way.

Upload server

Upload files based on service requirements.

The demo address

The demo address

reference

CocoaLumberjack

CocoaHTTPServer

conclusion

This article focuses on the real-time log viewing function in the LAN: In DEBUG mode or through console.app, you need to connect the mobile phone to the MAC computer to view real-time logs. There are also ways to include logging controls inside your APP, which can have an impact on your APP’s performance, as well as on your test results. Therefore, IN my opinion, the real-time APP logs can be directly viewed on the web page under the LAN to reduce the impact on the performance of the log control, and the logs can also be screened, copied and exported. So I personally think it’s worth a try.

Hit star if you want, Logger