每日一记 7.31

1、在每一个系统中log是必不可少的一个功能块。在平常的使用中有很多log日志框架,在这些日志框架中,只需要对配置文件进行配置后,就会自己生成log文件,并实现只保存自定义天数的日志。

  根据log日志框架的功能,自己写了一个类似log框架功能的函数。  

 
 
    //log文件夹目录的路径
    private static String logPath;

   /**     
   * 获取异常的详细信息     * @param ex
   *
@return */ public static String getExceptionAllinformation(Exception ex){ //创建一个空字符传 String sOut = ""; //获取异常信息数组 StackTraceElement[] trace = ex.getStackTrace(); //对异常信息进行拼接 for (StackTraceElement s : trace) { sOut = sOut + "\tat " + s + "\r\n"; } System.out.println("-----" + sOut); return sOut; } /**
   *在springboot的配置文件中配置log文件的位置
* spring boot配置文件中的值无法赋值给静态变量中,通过set方法为静态logPath赋值 * @param s */ @Value("${log.Path}") public void setLogPath(String s){ logPath = s; }   /** *对异常信息进行log文件的写入。 * @param text */ public static void WriteErrorLog(String text) { //查询是否存在存放log文件的文件夹 File logFolder = new File(logPath); //如果不存在,则进行创建。 if (!logFolder.exists()){ logFolder.mkdir(); } //获取当前系统时间 Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); String format = simpleDateFormat.format(date); //错误日志文件名.log String logFileName = format + ".log"; BufferedWriter bufferedWriter; try { //如果文件名存在则进行追加字符,文件名不存在则创建新文件 bufferedWriter = new BufferedWriter(new FileWriter(new File(logPath + logFileName),true)); SimpleDateFormat logInfoDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String logInfoDateStr = logInfoDate.format(date) + " ----- "; //将错误信息写入文件中 bufferedWriter.write(logInfoDateStr + text + "\r\n"); //关闭流 bufferedWriter.close(); } catch (IOException e) { System.out.println("日志文件创建失败!"); e.printStackTrace(); } //对时间进行计算 Calendar calendar=Calendar.getInstance(); calendar.setTime(new Date()); //减掉60天后的时间 calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)-60); //60天前的log文件名称 String oldLog = calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH)+1) + "-" + calendar.get(Calendar.DAY_OF_MONTH) + ".log"; //获取log文件 File file = new File(logPath + oldLog); //对文件是否存在进行判断 if (file.exists()){ //对文件进行删除 file.delete(); } }

2、在springboot中可以配置多个配置文件如在本地环境的配置文件,在测试环境的配置文件,在正式环境的配置文件。当环境发生改变以后,这样可以方便切换配置文件。操作如下:

在application.yml文件中的配置

spring:
 profiles:
  active: local

在项目中新建一个application-local.yml文件,在application-local.yml文件中配置项目所需要的配置。

同理,当需要配置其他环境时不需要修改application-local.yml文件,只需要在新建一个配置文件,并在application.yml文件中把local改成自己需要的文件名称。(“-”后面的名称,不加application-)

猜你喜欢

转载自www.cnblogs.com/sunshine-2018/p/11274095.html