Android uses Log4j to write logs to the SD card and dynamically modify the name of the output file
1. Log4j simple use 1. Download log4j. jar http://logging.apache.org/log4j/2.x/
2. Create 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 mobile phones, so use the code to configure the output path.
2. Android uses Log4j to write logs to the SD card and dynamically modify the name of the output file
1. Use the following code to set the output path and call it in the above init method.
Private static String getOutputPath (Context context, String name) {String rootPath = getSdcardPath (context); StringBuilder fileName = new StringBuilder (); // mobile 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) {// whether the SD card contains if (android. OS. environment. getExternalStorageState (). equals (android. OS. environment. MEDIA_MOUNTED) {// the SD card exists. return the root directory of the SD card, return Environment. getExternalStorageDirectory (). getPath ();} else {return context. getFilesDir (). getPath ();}}
2. Set SD card read and write permissions