First, log4j simple use 1. Download Log4j.jar http://logging.apache.org/log4j/2.x/
2. Creating Java Code
public class Loggers {public static Logger Logger = Logger. GetLogger (loggers. Class); public static void Init () { try { patternlayout patternlayout = new Patternlayout (); Patternlayout.setconversionpattern ("%d{yyyy-mm-dd HH:mm:ss}%m%n"); Fileappender Fileappender = new Fileappender (patternlayout, "D://log4j_info.log"); Logger.addappender (Fileappender); } catch (IOException e) { e.printstacktrace (); } } public static void Main (String argv[]) { init (); Logger.debug ("Hello, my name is Homer Simpson."); Logger.info ("We are the simpsons!"); Logger.warn ("Mmm ... Forbidden Donut. "); Logger.error ("Dear Baby, Welcome to Dumpsville. Population:you. "); Logger.fatal ("Eep.");} }
The code in INIT is to set the path and output file name based on different phones, so use code to configure the output path.
Second, Android use log4j write log to sd card, dynamically modify the output file name
1. Use the following code to set the output path, which is called in the Init method above
private static String Getoutputpath (context context, string name) {String RootPath = Getsdcardpath (context); StringBuilder fileName = new StringBuilder (); Phone model Filename.append (android.os.Build. MODEL); Filename.append ("-"); System version Filename.append ("Android_"); Filename.append (Android.os.Build.VERSION.RELEASE); SDK Version Filename.append ("_"); Filename.append (Android.os.Build.VERSION. SDK); Filename.append ("-"); String Path = RootPath + "/" + filename.tostring () + name; return path; } private static String Getsdcardpath (context context) {///SD card exists if (Android.os.Environment.getExterna Lstoragestate (). Equals (android.os.Environment. media_mounted)) {//SD card exists, return to SD card root directory return Environment.getexternalstoragedirectory (). GetPath (); } else {return Context.getfilesdir (). GetPath (); } }
2. Set the SD card read and Write permissions
< Create and delete file permissions!--sdcard-- <uses-permission android:name = "Android.permission.MOUNT_UNMOUNT_ Filesystems "/> <!--sdcard Write Data right-- <uses-permission android:name =" Android.permission.WRITE_ External_storage "/>
Android uses log4j to write logs to SD card, dynamically modify output file name