Create different android log classes


image.png
  • There's a scene like this.

Evil testers always like to find fault with us. Every time something goes wrong, they bring their mobile phones to us. Nima, what numbness, a bunch of bugs, and keep people away from work. Then there's no way. The test is God, so you have to take his cell phone to look for the log. Nima, the log comes out in a lot, and you have to roll to the end to see the latest error messages. That's a waste of time. Millions of grass-mud horses floated by... There are still a lot of bugs to fix, young, I don't want to be dragged to heaven, how to do...
duang...duang... This log artifact just came out of the sky and fell down....
You can set the file size of each log to be wooden.
Logs that can format and output beautiful styles are available in Wood.
The latest error information can be displayed in the front of the file with a wooden thread...
You can check the log s on your mobile phone on the intranet without leaving home.
It's really an artifact. There's wood.
Now lying in github Yes or no...
Welcome to see me Blog Yes or no...
Welcome to use FastAndrUtils android Quick Development Tool Class has its own features.

I bought too many advertisements. Sorry... Now let's get to the point.

  • Function list

  1. Log can be set to open and close
  2. Tag with Customizable Log
  3. File size saved by log can be set
  4. Can set whether to save log to sd card
  5. log is saved in html format, and with html style, it is more intuitive and convenient to view.
  6. Display the package name, class name, and line number of the current log. Click the line number to jump.
  7. log saving can insert header data, and it is more convenient to display the latest logs and view logs in the front.
  8. log with border output, more intuitive view
  9. Intranet Views log Data through Browser
  • There are pictures and facts.


log with Border Output

Intranet View log List

Content View of Intranet log
  • Function realization

Because there are a lot of codes, we will not paste the complete code, we will find some key to write. Complete code is available github Watch.

  • Basic configuration of log
 /**
     * Whether to turn on bebug mode
     */
    public FLogUtils debug(boolean debug) {
      ...
    }

    /**
     * Whether to save to sd card
     */
    public FLogUtils saveSD(boolean savesd) {
      ...
    }

    /**
     * Set the log file size
     */
    public FLogUtils setLogSize(int logSize) {
     ...
    }

    /**
     * Set up the log file directory
     */
    public FLogUtils setlogDir(String logDir) {
      ...
    }
  • Log log output
//Default tag log output
 public void e(String msg) {
        e("www.hotapk.cn", msg);
    }
//Custom log output
 public void e(String tag, String msg) {
     ...
    }

  • Gets the current class and row number of log
private String targetStackTraceMSg() {
        StackTraceElement targetStackTraceElement = getTargetStackTraceElement();
        if (targetStackTraceElement != null) {
            return "at " + targetStackTraceElement.getClassName() + "." + targetStackTraceElement.getMethodName() +
                    "(" + targetStackTraceElement.getFileName() + ":" + targetStackTraceElement.getLineNumber() + ")";

        } else {
            return "";
        }
    }

    private StackTraceElement getTargetStackTraceElement() {
        StackTraceElement targetStackTrace = null;
        boolean shouldTrace = false;
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();

        for (StackTraceElement stackTraceElement : stackTrace) {
            boolean isLogMethod = stackTraceElement.getClassName().equals(FLogUtils.class.getName());
            if (shouldTrace && !isLogMethod) {
                targetStackTrace = stackTraceElement;
                break;
            }
            shouldTrace = isLogMethod;
        }
        return targetStackTrace;
    }

  • log saved to sd card
 /**
     * Additional data
     *
     * @param filePath
     * @param content
     * @param header   Whether to add data to the head
     */
    public static void appendText(String filePath, String content, boolean header) {
        RandomAccessFile raf = null;
        FileOutputStream tmpOut = null;
        FileInputStream tmpIn = null;
        try {
            File tmp = File.createTempFile("tmp", null);
            tmp.deleteOnExit();//Delete when JVM exits

            raf = new RandomAccessFile(filePath, "rw");
            //Create a temporary folder to hold the data after the insertion point
            tmpOut = new FileOutputStream(tmp);
            tmpIn = new FileInputStream(tmp);
            long fileLength = 0;
            if (!header) {
                fileLength = raf.length();
            }
            raf.seek(fileLength);
            /**Read the contents after the insertion point into the temporary folder**/

            byte[] buff = new byte[1024];
            //The number of bytes used to save temporary reads
            int hasRead = 0;
            //Loop the contents after the insertion point
            while ((hasRead = raf.read(buff)) > 0) {
                // Write read data into temporary files
                tmpOut.write(buff, 0, hasRead);
            }
            //Insert data that you need to specify to add
            raf.seek(fileLength);//Return to the original insert
            //Additional requirements
            raf.write(content.getBytes());
            //Finally, add the contents of the Interim Document
            while ((hasRead = tmpIn.read(buff)) > 0) {
                raf.write(buff, 0, hasRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (tmpOut!=null){
                try {
                    tmpOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (tmpIn!=null){
                try {
                    tmpIn.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (raf!=null){
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

The above is the realization of the basic user-defined log function, Google on a pile of counterfeit drugs came out...
The following is the key to my log tool class...

Make your log accessible on the Intranet

  1. Using the well-known nanohttpd class, android can be used as an intranet server
  • Inheritance of NanoHTTPD class
public class LogNetServer extends NanoHTTPD {
    private Context context;

    public LogNetServer(int port) {
        super(port);
    }

    public LogNetServer(String hostname, int port) {
        super(hostname, port);
    }

    public LogNetServer(int port, Context context) {
        super(port);
        this.context = context;
    }


    @Override
    public Response serve(IHTTPSession session) {
        String file_name = session.getUri().substring(1);
        StringBuffer br = new StringBuffer();
        String header = FAssetsARawUtils.getAssetsToString("baidu.html", context);
        br.append(header);
        String filedir = FLogUtils.getInstance().getLogFileDir();
        FLogUtils.getInstance().e("Test the effect-----");
        if (file_name.isEmpty()) {
            File[] files = FFileUtils.getFiles(filedir);
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    br.append(
                            "<div class=\"exp\"><a href = "
                                    + "/log?logfile="
                                    + files[i].getName() +
                                    " target=\"_blank\" >" + files[i].getName() +
                                    "</a ></div>"
                    );
                }

            }
        } else {
            Map<String, String> parms = session.getParms();
            if (parms.containsKey("logfile")) {
                String name = parms.get("logfile");
                String logstr = FFileUtils.readFile(filedir + "/" + name);
                br.append(logstr);
            } else {
                br.append("Something the matter");
            }

        }
        br.append("</body></html>");

        return newFixedLengthResponse(Response.Status.OK, "text/html", br.toString());
    }
}
  • FLogUtils creates methods to start and close Web Server services
/**
     * Start log's Web Server Service
     *
     * @param port
     * @param context
     */
    public void startLogServer(int port, Context context) {
        if (testHttpd == null) {
            synchronized (FLogUtils.class) {
                if (testHttpd == null) {
                    testHttpd = new LogNetServer(port, context.getApplicationContext());
                }
            }
        }
        try {
            testHttpd.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

 /**
     * Close log's Web Server Service
     */
    public void stopLogServer() {
        if (testHttpd != null && testHttpd.isAlive()) {
            testHttpd.stop();
        }
    }

  • There's also an html file
<!Doctype html>
<html xmlns=http://www.w3.org/1999/xhtml>
<head>
    <meta http-equiv=Content-Type content="text/html;charset=utf-8">
    <title>less code , less bug</title>

    <style type="text/css">
.dotted {border-style: dotted;
margin-top: 36px;}
.exp{ border-bottom:1px dashed #F00}
div {padding: 10px;}
.redcolor{ color:#F00;}
    </style>

</head>
<body>

After a long time, I finally finished this log tool article. It's no wonder that the literary grace is not good.
Look at the complete code, please move on github

Keywords: github Session Web Server Mobile

Added by pauper_i on Fri, 24 May 2019 21:48:15 +0300