Android 使用Log4j把日志写入SD卡,动态修改输出文件名称
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."); } }
private static String getOutputPath(Context context, String name) { String rootPath = getSdcardPath(context); StringBuilder fileName = new StringBuilder(); // 手机型号 fileName.append(android.os.Build. MODEL); fileName.append( "-"); // 系统版本 fileName.append( "Android_"); fileName.append(android.os.Build.VERSION.RELEASE ); // SDK版本 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卡是否存在 if (android.os.Environment.getExternalStorageState().equals(android.os.Environment. MEDIA_MOUNTED)) { // SD卡存在,返回SD卡根目录 return Environment.getExternalStorageDirectory().getPath(); } else { return context.getFilesDir().getPath(); } }
<!-- SDCard中创建与删除文件权限 --> <uses-permission android:name ="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <!-- SDCard写入数据权限 --> <uses-permission android:name ="android.permission.WRITE_EXTERNAL_STORAGE" />
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。