Android outputs exception information to the file

Source: Internet
Author: User

When a program is in the development stage, you can view errors, exceptions, and other information in the development environment. However, when the program is handed over to the test environment or runs on a real device out of the development environment, you cannot be notified of the error.

The only way is to record the log to a text file and view the cause of the error. Therefore, it is very important to record data from days to external storage devices.

There are several methods to record logs. The following describes them one by one.

Method 1: Use the android built-in log class to implement:

This is reprinted

Package COM. sample; import Java. io. bufferedwriter; import Java. io. file; import Java. io. filewriter; import Java. io. ioexception; import Java. text. simpledateformat; import Java. util. calendar; import Java. util. date; import android. util. log;/*** with log file input, log debugging for controllable switches ** @ author baohang * @ version 1.0 * @ data 2012-2-20 */public class mylog {Private Static Boolean mylog_switch = true; // log file General switch Private Static Boolean mylog_write_to_file = true; // log writing switch Private Static char mylog_type = 'V'; // enter the log type, W indicates that only alarm information is output, and V indicates that all output information is Private Static string mylog_path_sdcard_dir = "/sdcard/"; // path of the log file in sdcard: Private Static int sdcard_log_file_save_days = 0; // The maximum number of days for saving log files on the SD card. Private Static string mylogfilename = "log.txt "; // name of the log file output in this class: Private Static simpledateformat mylogsdf = new simpledateformat ("yyyy-mm-dd hh: mm: SS "); // log output format Private Static simpledateformat logfile = new simpledateformat ("yyyy-mm-dd"); // Log File Format public static void W (string tag, object MSG) {// warning information log (TAG, MSG. tostring (), 'w');} public static void E (string tag, object MSG) {// error message log (TAG, MSG. tostring (), 'E');} public static void D (string tag, object MSG) {// debug information log (TAG, MSG. tostring (), 'D');} public static void I (string tag, object MSG) {// log (TAG, MSG. tostring (), 'I');} public static void V (string tag, object MSG) {log (TAG, MSG. tostring (), 'V');} public static void W (string tag, string text) {log (TAG, text, 'w ');} public static void E (string tag, string text) {log (TAG, text, 'E');} public static void D (string tag, string text) {log (tag, text, 'D');} public static void I (string tag, string text) {log (TAG, text, 'I');} public static void V (string tag, string text) {log (TAG, text, 'V');}/*** according to tag, MSG, and level, output log ** @ Param tag * @ Param MSG * @ Param level * @ return void * @ since v 1.0 */Private Static void log (string tag, string MSG, char level) {If (mylog_switch) {If ('E' = level & ('E' = mylog_type | 'V' = mylog_type )) {// output error message log. E (TAG, MSG);} else if ('W' = level & ('W' = mylog_type | 'V' = mylog_type) {log. W (TAG, MSG);} else if ('D' = level & ('D' = mylog_type | 'V' = mylog_type) {log. D (TAG, MSG);} else if ('I' = level & ('D' = mylog_type | 'V' = mylog_type) {log. I (TAG, MSG);} else {log. V (TAG, MSG);} If (mylog_write_to_file) writelogtofile (string. valueof (level), Tag, MSG) ;}/ *** open the log file and write the log ** @ return ***/Private Static void writelogtofile (string mylogtype, string tag, string text) {// create or open a log file date nowtime = new date (); string needwritefiel = logfile. format (nowtime); string needwritemessage = mylogsdf. format (nowtime) + "" + mylogtype + "" + tag + "" + text; file = new file (mylog_path_sdcard_dir, needwritefiel + mylogfilename ); try {filewriter filerwriter = new filewriter (file, true); // The following parameter indicates whether to connect to the original data in the file, without overwriting bufferedwriter bufwriter = new bufferedwriter (filerwriter ); bufwriter. write (needwritemessage); bufwriter. newline (); bufwriter. close (); filerwriter. close ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace () ;}}/*** Delete the specified Log File **/public static void delfile () {// Delete the log file string needdelfiel = logfile. format (getdatebefore (); file = new file (mylog_path_sdcard_dir, needdelfiel + mylogfilename); If (file. exists () {file. delete () ;}}/*** get the date a few days before the current time to get the log file name to be deleted **/Private Static date getdatebefore () {date nowtime = new date (); Calendar now = calendar. getinstance (); now. settime (nowtime); now. set (calendar. date, now. get (calendar. date)-sdcard_log_file_save_days); return now. gettime ();}}

Method 2:

Use the log management provided by a third party. For example, log4j in Apache is a powerful log management function. It can be implemented through simple configuration, which is very convenient to use, android requires two. JAR File

Are the log4j-1.2.17.jar under Apache, there are android-logging-log4j-1.0.3.jar files (android need auxiliary tools)

I have uploaded: 1, click open link 2, and click open link

Below is a simple log management class encapsulated by myself, which is sufficient for simple log records.

The Code is as follows:

Package COM. zhongxin. stock. util; import Java. io. file; import Java. io. filenotfoundexception; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. text. simpledateformat; import Java. util. calendar; import Java. util. date; import Org. apache. log4j. logger; import android. OS. environment; import android. util. log; import de. mindpipe. android. logging. log4j. logconfigurator; public class loggermanager {P Rivate static int sdcard_log_file_save_days = 3; // The maximum number of days that log files are stored in the SD card. Private Static simpledateformat logfile = new simpledateformat ("yyyy-mm-dd "); // Log File Format: Private Static logger; private loggermanager () {}/ *** Get log output instance * @ return */public static logger getloggerinstance () {If (logger = NULL) {initlog (); logger = logger. getlogger (loggermanager. class. getclass (); // logger. debug ("init log4j log \ n ");} Return logger;} Private Static void initlog () {logconfigurator = new logconfigurator (); file sdpath = new file (environment. getexternalstoragedirectory (). getabsolutepath () + file. separator + "zhongxinlog"); If (! Sdpath. exists () {sdpath. mkdirs ();} file logfile = new file (sdpath, logfile. format (new date () + "applog" + ". TXT "); If (! Logfile. exists () {try {logfile. createnewfile ();} catch (ioexception e) {e. printstacktrace () ;}} logconfigurator. setfilename (logfile. getabsolutepath (); // logconfigurator. setrootlevel (level. debug); logconfigurator. setfilepattern ("% d %-5 p [% c {2}]-[% L] % m % N"); logconfigurator. setmaxfilesize (1024*1024*5); logconfigurator. setimmediateflush (true); logconfigurator. configure ();} public static void C Leanfile () {// If you only need to delete part of the content in the file, you must perform some operations on the string here: String cleanstr = ""; fileoutputstream = NULL; file file = new file (environment. getexternalstoragedirectory (). getabsolutepath () + file. separator + "zhongxinlog", "appproplemlog" + ". TXT "); try {fileoutputstream = new fileoutputstream (File); fileoutputstream. write (cleanstr. getbytes (); fileoutputstream. close ();} catch (filenotfoundexception e) {e. P Rintstacktrace ();} catch (ioexception e) {e. printstacktrace () ;}} public static string getexceptionmessage (exception ex) {string result = ""; stacktraceelement [] STEs = ex. getstacktrace (); For (INT I = 0; I <STEs. length; I ++) {result = Result + STEs [I]. getclassname () + ". "+ STEs [I]. getmethodname () + "" + STEs [I]. getlinenumber () + "line" + "\ r \ n";} return result;}/*** delete a specified Log File **/public static void named achefile (Final string DIR) {string needdelfiel = logfile. Format (getdatebefore (); file cachedir = new file (DIR); If (! Cachedir. exists () {return;} log. E (Dir, "-------- total" + cachedir. listfiles (). length + "cached files"); // prevents anrfile [] files = cachedir from being caused by listfiles. listfiles (); For (INT I = 0; I <files. length; I ++) {files [I]. delete () ;}}/*** get the date a few days before the current time to get the log file name to be deleted **/Private Static date getdatebefore () {date nowtime = new date (); Calendar now = calendar. getinstance (); now. settime (nowtime); now. set (calendar. date, now. get (calendar. date)-sdcard_log_file_save_days); return now. gettime ();}}

Loggerm = loggermanager. getloggerinstance (); try {// Exception Code may be generated} catch (exception e) {loggerm. debug (loggermanager. getexceptionmessage (e ));}

Log result:

2013-04-18 13:08:57,678 DEBUG [lang.Class]-[28] init log4j log2013-04-18 13:24:07,679 DEBUG [lang.Class]-[237] org.apache.http.conn.scheme.PlainSocketFactory.connectSocket  121lineorg.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection  144lineorg.apache.http.impl.conn.AbstractPoolEntry.open  164lineorg.apache.http.impl.conn.AbstractPooledConnAdapter.open  119lineorg.apache.http.impl.client.DefaultRequestDirector.execute  365lineorg.apache.http.impl.client.AbstractHttpClient.execute  555lineorg.apache.http.impl.client.AbstractHttpClient.execute  487lineorg.apache.http.impl.client.AbstractHttpClient.execute  465linecom.zhongxin.stock.ActivityMain$ThreadReadStock.run  231linejava.lang.Thread.run  856line2013-04-18 13:24:07,682 DEBUG [lang.Class]-[237] org.apache.http.conn.scheme.PlainSocketFactory.connectSocket  121lineorg.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection  144lineorg.apache.http.impl.conn.AbstractPoolEntry.open  164lineorg.apache.http.impl.conn.AbstractPooledConnAdapter.open  119lineorg.apache.http.impl.client.DefaultRequestDirector.execute  365lineorg.apache.http.impl.client.AbstractHttpClient.execute  555lineorg.apache.http.impl.client.AbstractHttpClient.execute  487lineorg.apache.http.impl.client.AbstractHttpClient.execute  465linecom.zhongxin.stock.ActivityMain$ThreadReadStock.run  231linejava.lang.Thread.run  856line

We can see that the record is clear and clear.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.