封装了本地日志,可以通过config
文件动态控制log的打印,方便上线前日志打印的检查,并且如果在测试环境下,日志等级为i以上的日志都会存文件,并且文件以日期命名,最大数量为5,可以配置。

代码如下所示:

public final class EBLog {private static final String TAG = EBLog.class.getName();/*** Define the log priority.*/private static LogType logType;private static HashMap<Integer, String> level = new HashMap<>();static {level.put(2, "verbose");level.put(3, "debug");level.put(4, "info");level.put(5, "warn");level.put(6, "error");level.put(7, "asset");if (Config.ISRELEASE) {setLogType(LogType.asset);} else {setLogType(LogType.verbose);}}private EBLog() {}/*** Get the log level.** @return log level*/public static LogType getLogType() {return logType;}/*** Set the log level for the application.** @param logType the value to be set.*/public static void setLogType(LogType logType) {EBLog.logType = logType;i(TAG, "logType: " + logType);}/*** Send a  log message.** @param tag Used to identify the source of a log message. It usually*            identifies the class or activity where the log call occurs.* @param msg The message you would like logged.*/public static int v(String tag, String msg) {StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[3];return ElectronicBrandPrintln(LogType.verbose.value(), tag, msg,stackTraceElement);}/*** Send a  log message and log the exception.** @param tag Used to identify the source of a log message. It usually*            identifies the class or activity where the log call occurs.* @param msg The message you would like logged.* @param tr  An exception to log*/public static int v(String tag, String msg, Throwable tr) {StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[3];return ElectronicBrandPrintln(LogType.verbose.value(), tag, msg + '\n' + getStackTraceString(tr),stackTraceElement);}/*** Send a log message.** @param tag Used to identify the source of a log message. It usually*            identifies the class or activity where the log call occurs.* @param msg The message you would like logged.*/public static int d(String tag, String msg) {StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[3];return ElectronicBrandPrintln(LogType.debug.value(), tag, msg,stackTraceElement);}/*** Send a  log message and log the exception.** @param tag Used to identify the source of a log message. It usually*            identifies the class or activity where the log call occurs.* @param msg The message you would like logged.* @param tr  An exception to log*/public static int d(String tag, String msg, Throwable tr) {StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[3];return ElectronicBrandPrintln(LogType.debug.value(), tag, msg + '\n' + getStackTraceString(tr),stackTraceElement);}/*** Send an log message.** @param tag Used to identify the source of a log message. It usually*            identifies the class or activity where the log call occurs.* @param msg The message you would like logged.*/public static int i(String tag, String msg) {StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[3];return ElectronicBrandPrintln(LogType.info.value(), tag, msg,stackTraceElement);}/*** Send a log message and log the exception.** @param tag Used to identify the source of a log message. It usually*            identifies the class or activity where the log call occurs.* @param msg The message you would like logged.* @param tr  An exception to log*/public static int i(String tag, String msg, Throwable tr) {StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[3];return ElectronicBrandPrintln(LogType.info.value(), tag, msg + '\n' + getStackTraceString(tr),stackTraceElement);}/*** Send a log message.** @param tag Used to identify the source of a log message. It usually*            identifies the class or activity where the log call occurs.* @param msg The message you would like logged.*/public static int w(String tag, String msg) {StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[3];return ElectronicBrandPrintln(LogType.warn.value(), tag, msg,stackTraceElement);}/*** Send a log message and log the exception.** @param tag Used to identify the source of a log message. It usually*            identifies the class or activity where the log call occurs.* @param msg The message you would like logged.* @param tr  An exception to log*/public static int w(String tag, String msg, Throwable tr) {StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[3];return ElectronicBrandPrintln(LogType.warn.value(), tag, msg + '\n' + getStackTraceString(tr),stackTraceElement);}/*** Checks to see whether or not a log for the specified tag is loggable at* the specified level. The default level of any tag is set to INFO. This* means that any level above and including INFO will be logged. Before you* make any calls to a logging method you should check to see if your tag* should be logged. You can change the default level by setting a system* property: 'setprop log.tag.&lt;YOUR_LOG_TAG> &lt;LEVEL>' Where level is* either value of LogType, or SUPPRESS. SUPRESS will turn off all logging* for your tag. You can also create a local.prop file that with the* following in it: 'log.tag.&lt;YOUR_LOG_TAG>=&lt;LEVEL>' and place that in* /data/local.prop.** @param tag   The tag to check.* @param level The level to check, value of LogType.* @return Whether or not that this is allowed to be logged.* @throws IllegalArgumentException is thrown if the tag.length() > 23.*/public static native boolean isLoggable(String tag, int level);/** Send a {@link #WARN} log message and log the exception.* * @param tag Used to identify the source of a log message. It usually* identifies the class or activity where the log call occurs.* * @param tr An exception to log*/public static int w(String tag, Throwable tr) {StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[3];return ElectronicBrandPrintln(LogType.warn.value(), tag, getStackTraceString(tr),stackTraceElement);}/*** Send an log message.** @param tag Used to identify the source of a log message. It usually*            identifies the class or activity where the log call occurs.* @param msg The message you would like logged.*/public static int e(String tag, String msg) {StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[3];return ElectronicBrandPrintln(LogType.error.value(), tag, msg,stackTraceElement);}/*** Send a log message and log the exception.** @param tag Used to identify the source of a log message. It usually*            identifies the class or activity where the log call occurs.* @param msg The message you would like logged.* @param tr  An exception to log*/public static int e(String tag, String msg, Throwable tr) {StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[3];return ElectronicBrandPrintln(LogType.error.value(), tag, msg + "\n" + getStackTraceString(tr),stackTraceElement);}/*** Handy function to get a loggable stack trace from a Throwable** @param tr An exception to log*/private static String getStackTraceString(Throwable tr) {if (tr == null) {return "";}StringWriter sw = new StringWriter();PrintWriter pw = new PrintWriter(sw);tr.printStackTrace(pw);return sw.toString();}private static int ElectronicBrandPrintln(int priority, String tag, String msg,StackTraceElement stackTraceElement) {if (priority >= logType.value()) {if (!Config.ISRELEASE && priority >= 4) {ThreadPoolService.addTask(new LogSaveUtils(getLogInfo( priority, tag, msg,stackTraceElement)));}return android.util.Log.println(priority, tag, msg);} else {return -1;}}/*** May be verbose, debug, info, warn, error, asset.** @author coleman*/public static enum LogType {verbose(2), debug(3), info(4), warn(5), error(6), asset(7);private final int type;private LogType(int type) {this.type = type;}public int value() {return type;}public static LogType instanse(int i) {LogType type = verbose;switch (i) {case 2:type = verbose;break;case 3:type = debug;break;case 4:type = info;break;case 5:type = warn;break;case 6:type = error;break;case 7:type = asset;break;default:type = null;break;}return type;}}/*** 保存日志所包含的信息** @param tag* @param priority* @return*/private static String getLogInfo(int priority, String tag, String msg,StackTraceElement stackTraceElement) {StringBuilder logInfoStringBuilder = new StringBuilder();// 获取线程名String threadName = Thread.currentThread().getName();// 获取类名.即包名+类名String className = stackTraceElement.getClassName();// 获取方法名称String methodName = stackTraceElement.getMethodName();// 获取生日输出行数int lineNumber = stackTraceElement.getLineNumber();logInfoStringBuilder.append(GeneralUtils.getCurrentTime(Constants.YEAR_MONTH_DAY_HOUR_MINUTE_SECOND));logInfoStringBuilder.append("  [");logInfoStringBuilder.append(threadName).append("]   ");logInfoStringBuilder.append(className).append("   ");logInfoStringBuilder.append(level.get(priority)).append("/").append(tag);logInfoStringBuilder.append("   [methodName=" + methodName).append("]   ");logInfoStringBuilder.append("[lineNumber=" + lineNumber);logInfoStringBuilder.append(" ]   ");logInfoStringBuilder.append(msg);return logInfoStringBuilder.toString();}
}

线程池类代码如下:

/*** <线程池管理>** @author caoyinfei* @version [版本号, 2016/6/21]* @see [相关类/方法]* @since [V1]*/
public class ThreadPoolService {private static ExecutorService executor = Executors.newCachedThreadPool();public static void addTask(LogSaveUtils logSaveUtils){executor.execute(logSaveUtils);}
}

文件保存类代码如下:

/*** <日志文件处理类>** @author caoyinfei* @version [版本号, 2016/6/21]* @see [相关类/方法]* @since [V1]*/
public class LogSaveUtils implements Runnable {private String content;public LogSaveUtils(String content) {this.content = content;}/*** 文件最大个数*/private static final int MAX_SIZE = 5;/*** 文件名后缀*/private static String FILE_NAME = ".log";/*** 文件*/private File file;/*** 输出流*/private RandomAccessFile randomAccessFile;private SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd");// 日志名称格式@Overridepublic void run() {saveToFile();}/*** 保存到本地文件*/private synchronized void saveToFile() {try {deleteFile();LocalFileStorageManager localFileStorageManager = BridgeFactory.getBridge(Bridges.LOCAL_FILE_STORAGE);String fileName = localFileStorageManager.getVersionLogPath() + Config.LOG_FILE_NAME + GeneralUtils.getCurrentTime(Constants.YEAR_MONTH_DAY) + FILE_NAME;file = new File(fileName);randomAccessFile = new RandomAccessFile(file, "rw");randomAccessFile.seek(file.length());randomAccessFile.write(content.getBytes("utf-8"));randomAccessFile.write("\r\n".getBytes());} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {randomAccessFile.close();} catch (Exception e) {}}}/*** 文件超过最大个数则删除最旧的文件*/private void deleteFile() {LocalFileStorageManager localFileStorageManager = BridgeFactory.getBridge(Bridges.LOCAL_FILE_STORAGE);File root = new File(localFileStorageManager.getVersionLogPath());if (root.isDirectory()) {File[] listFiles = root.listFiles();if (listFiles != null && listFiles.length >= MAX_SIZE) {Arrays.sort(listFiles, new FileComparator());listFiles[0].delete();}}}class FileComparator implements Comparator<File> {public int compare(File file1, File file2) {String createInfo1 = getFileNameWithoutExtension(file1.getName());String createInfo2 = getFileNameWithoutExtension(file2.getName());try {Date create1 = dataFormat.parse(createInfo1);Date create2 = dataFormat.parse(createInfo2);if (create1.before(create2)) {return -1;} else {return 1;}} catch (ParseException e) {return 0;}}}/*** 去除文件的扩展类型(.log)** @param fileName* @return*/private String getFileNameWithoutExtension(String fileName) {try {return fileName.substring(fileName.indexOf(".")+1, fileName.lastIndexOf("."));} catch (Exception e) {return "";}}}
/*** <上线前需要更改的配置文件>** @author caoyinfei* @version [版本号, 2016/6/21]* @see [相关类/方法]* @since [产品/模块版本]*/
public class Config {/*** 是否为release版本*/public static final boolean ISRELEASE = false;/*** 日志文件前缀*/public static final String LOG_FILE_NAME = "eb-p.";}

文件目录的创建代码:

    /*** <日志目录>* <功能详细描述>* @return*/public static String getVersionLogPath() {return FileUtil.createNewFile(getCacheFilePath() + FOLDER_NAME_LOG + File.separator);}
    public static String createNewFile(String path) {File dir = new File(path);if (!dir.exists()) {dir.mkdirs();}return path;}

保存的文件如下所示:

eb-p.2016-06-23.log
eb-p.2016-06-28.log

文件中的日志如下所示:

2016-06-23 16:43:17  [main]   com.test.electronicbrand.capabilities.log.EBLog   info/com.test.electronicbrand.capabilities.log.EBLog   [methodName=setLogType]   [lineNumber=90 ]   logType: verbose
2016-06-23 16:43:17  [main]   com.test.electronicbrand.ui.personcenter.LoginActivity   info/sdsd   [methodName=initData]   [lineNumber=57 ]   ssdsd
2016-06-23 16:43:17  [main]   com.test.electronicbrand.ui.personcenter.LoginActivity   info/aaa   [methodName=setHeader]   [lineNumber=64 ]   dfdf

如有错误欢迎指出来,一起学习。

log日志打印封装,并保存到本地文件相关推荐

  1. Android 异常崩溃日志,捕捉并保存到本地

    Android 异常崩溃日志,捕捉并保存到本地: 前几天因为在省公安厅做一个通讯类之类的应用:碰到个问题,就是download人员信息将信息保存到本地数据库完成的时候,菊花转还没有dismission ...

  2. python保存运行结果下次使用_将python运行结果保存至本地文件中的示例讲解

    一.建立文件,保存数据 1.使用python中内置的open函数 打开txt文件 #mode 模式 #w 只能操作写入 r 只能读取 a 向文件追加 #w+ 可读可写 r+可读可写 a+可读可追加 # ...

  3. java通过url获取网页内容_Java语言通过URL读取网页数据并保存到本地文件(代码实例)...

    本文主要向大家介绍了Java语言通过URL读取网页数据并保存到本地文件(代码实例),通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助. Java通过URL读取网页数据并保存到本地文件(代码 ...

  4. Jmeter把响应数据结果保存到本地文件

    最近做一个性能压测,需要用接口获取大量的数据,并获取该接口返回的一个字段值,于是找了如何把响应数据结果保存到本地文件. 如图,某接口需要用如图所示字段入参. 步骤一:先用正则表达式获取该字段的内容 步 ...

  5. Python爬取起点小说并保存到本地文件夹和MongoDB数据库中

    Python爬取起点小说并保存到本地MongoDB数据库中 工具:Python3.7 + Mongo4.0 + Pycharm """ 爬取起点小说<诡秘之主> ...

  6. 爬虫实战5:爬取全部穿越火线武器的图片以武器名称命名保存到本地文件

    申明:资料来源于网络及书本,通过理解.实践.整理成学习笔记. 文章目录 穿越火线官网 完整代码 运行结果 穿越火线官网 完整代码 import requests# 循环33次,官网武器库展示有33页 ...

  7. mac挂adb,并把日志保存在本地文件中

    挂adb,使用logcat把log跑到文件中,并筛选出来 以下是挂adb touch .base_profile open .base_profile export ANDROID_HOME=sdk路 ...

  8. php 图片保存到本地文件,php 远程图片保存到本地的函数类

    php 远程图片保存到本地的函数类 发布于 2014-10-06 14:15:40 | 78 次阅读 | 评论: 0 | 来源: 网友投递 PHP开源脚本语言PHP(外文名: Hypertext Pr ...

  9. python爬取正确但不出文件_python爬取糗事百科,该如何正确保存到本地文件夹?报错-问答-阿里云开发者社区-阿里云...

    我的程序已经可以爬取网络内容,但不太清楚怎么保存到当地文件夹,用网上方法试着做,但是有报错 import urllib import urllib.request import requests ## ...

最新文章

  1. 江苏“超牛”女博导:16岁考入北大,跨专业读博,成为全球第4个获此奖项的学者!...
  2. oracle共享时监听,Oracle监听---共享连接参数配置介绍
  3. 数据中心ups电源七个故障分析
  4. 快速打开计算机磁盘的软件,提升电脑运行效率, 你需要快速整理磁盘碎片的工具...
  5. linux c之wait和waitpid函数的用法和总结
  6. WinInet:HTTPS 请求出现无效的证书颁发机构的处理
  7. 2. XML 的用途
  8. 3DMM(人脸3D形变统计模型)
  9. 苹果手机电池健康怎么看_打开手机这个功能,就能知道手机电池的健康度,安卓苹果都可以!...
  10. android原生app转成web,转战WebApp: 最适合Android开发者的WebApp框架
  11. JTAG和SWD定义
  12. iPhone/iPad屏幕投屏镜像到PC或Mac上面教程分享
  13. 小米扫地机器人换了边刷很响_扫地机器人边刷常见问题解决办法,故障排除
  14. 直播开发中音画不同步如何解决
  15. Notepad++装JsonViewer插件
  16. 100.s1-来电归属地的显示
  17. setup facatory9.0打包详细教程(含静默安装和卸载)
  18. 超级详细的PostgreSQL创建数据库操作并附带图文
  19. 微信小程序 swoole简单聊天室
  20. 如何查询计算机已连接wife的密码错误,三种方法查询已连接 WiFi 的密码,简单实用!...

热门文章

  1. hp服务器在线扩容,惠普DL380G9的服务器,内存扩容,混插不同容量规格是否可以...
  2. [勇者闯LeetCode] 112. Path Sum
  3. 人工智能政策再加码 中庆录播另辟新路径
  4. RabbitMQ(mq) 如何处理高并发、负载均衡、消息幂等性、丢失、消息顺序错乱问题?
  5. 计算机应用基础案例教程习题答案,新编计算机应用基础案例教程上机指导与习题集(朱尽蓉)-习题答案.doc...
  6. 基于hexo搭建个人博客
  7. vue获取dom元素高度的方法
  8. python时间函数带时区_Python pytz时区函数返回的时区为9分钟 - python
  9. java游戏boss是冰龙_炉石传说冒险模式冰龙区BOSS克尔苏加德打法攻略
  10. 让python飞:形象理解python 列表、元组、字典、集合、运算符