abstractrolloverlog.java

来自「RESIN 3.2 最新源码」· Java 代码 · 共 870 行 · 第 1/2 页

JAVA
870
字号
	if (_isRollingOver || now < _nextRolloverCheckTime)	  return;	_isRollingOver = isRollingOver = true;      	_nextRolloverCheckTime = now + _rolloverCheckPeriod;	long lastPeriodEnd = _nextPeriodEnd;	if (_rolloverCron != null)	  _nextPeriodEnd = _rolloverCron.nextTime(now);	else	  _nextPeriodEnd = Period.periodEnd(now, getRolloverPeriod());	Path path = getPath();	if (lastPeriodEnd < now) {	  closeLogStream();      	  if (getPathFormat() == null) {	    savedPath = getArchivePath(lastPeriodEnd - 1);	  }	  /*	    if (log.isLoggable(Level.FINE))	    log.fine(getPath() + ": next rollover at " +	    QDate.formatLocal(_nextPeriodEnd));	  */	}	else if (path != null && getRolloverSize() <= path.getLength()) {	  closeLogStream();	  if (getPathFormat() == null) {	    savedPath = getArchivePath(now);	  }	}	long nextPeriodEnd = _nextPeriodEnd;	if (_nextPeriodEnd < _nextRolloverCheckTime && _nextPeriodEnd > 0)	  _nextRolloverCheckTime = _nextPeriodEnd;      }      // archiving of path is outside of the synchronized block to      // avoid freezing during archive      if (savedPath != null) {	_savedPath = savedPath;	isRollingOver = false;	ThreadPool.getThreadPool().startPriority(_archiveTask);	Thread.yield();      }    } finally {      synchronized (this) {	if (isRollingOver) {	  _isRollingOver = false;	  flushTempStream();	}      }    }  }  /**   * Tries to open the log.   */  private void openLog()  {    closeLogStream();        try {      WriteStream os = _os;      _os = null;      if (os != null)	os.close();    } catch (Throwable e) {      // can't log in log routines    }          Path path = getPath();    if (path == null) {      path = getPath(Alarm.getCurrentTime());    }        try {      if (! path.getParent().isDirectory())	path.getParent().mkdirs();    } catch (Throwable e) {      logWarning(L.l("Can't create log directory {0}", path.getParent()), e);    }    Exception exn = null;        for (int i = 0; i < 3 && _os == null; i++) {      try {	_os = path.openAppend();      } catch (IOException e) {	exn = e;      }    }    String pathName = path.getPath();    try {      if (pathName.endsWith(".gz")) {	_zipOut = _os;	_os = Vfs.openWrite(new GZIPOutputStream(_zipOut));      }      else if (pathName.endsWith(".zip")) {	throw new ConfigException("Can't support .zip in path-format");      }    } catch (Exception e) {      if (exn == null)	exn = e;    }    if (exn != null)      logWarning(L.l("Can't create log directory {0}", path), exn);  }  private void movePathToArchive(Path savedPath)  {    if (savedPath == null)      return;        closeLogStream();        Path path = getPath();        String savedName = savedPath.getTail();    try {      if (! savedPath.getParent().isDirectory())	savedPath.getParent().mkdirs();    } catch (Throwable e) {      logWarning(L.l("Can't open archive directory {0}",		     savedPath.getParent()),		 e);    }    try {      if (path.exists()) {        WriteStream os = savedPath.openWrite();        OutputStream out;        if (savedName.endsWith(".gz"))          out = new GZIPOutputStream(os);        else if (savedName.endsWith(".zip"))           out = new ZipOutputStream(os);        else          out = os;        try {          path.writeToStream(out);        } finally {          try {            out.close();          } catch (Throwable e) {            // can't log in log rotation routines          }          try {            if (out != os)              os.close();          } catch (Throwable e) {            // can't log in log rotation routines          }        }      }    } catch (Throwable e) {      logWarning(L.l("Error rotating logs"), e);    }    try {      try {        if (! path.truncate())          path.remove();      } catch (IOException e) {        path.remove();        throw e;      }    } catch (Exception e) {      logWarning(L.l("Error truncating logs"), e);    }    if (_rolloverCount > 0)      removeOldLogs();  }  /**   * Removes logs passing the rollover count.   */  private void removeOldLogs()  {    try {      Path path = getPath();      Path parent = path.getParent();      String []list = parent.list();      ArrayList<String> matchList = new ArrayList<String>();      Pattern archiveRegexp = getArchiveRegexp();      for (int i = 0; i < list.length; i++) {	Matcher matcher = archiveRegexp.matcher(list[i]);	if (matcher.matches())	  matchList.add(list[i]);      }      Collections.sort(matchList);      if (_rolloverCount <= 0 || matchList.size() < _rolloverCount)	return;      for (int i = 0; i + _rolloverCount < matchList.size(); i++) {	try {	  parent.lookup(matchList.get(i)).remove();	} catch (Throwable e) {	}      }    } catch (Throwable e) {    }  }  private Pattern getArchiveRegexp()  {    StringBuilder sb = new StringBuilder();    String archiveFormat = getArchiveFormat();    for (int i = 0; i < archiveFormat.length(); i++) {      char ch = archiveFormat.charAt(i);      switch (ch) {      case '.':  case '\\': case '*': case '?': case '+':      case '(': case ')': case '{': case '}': case '|':	sb.append("\\");	sb.append(ch);	break;      case '%':	sb.append(".+");	i++;	break;      default:	sb.append(ch);	break;      }    }    return Pattern.compile(sb.toString());  }  /**   * Returns the path of the format file   *   * @param time the archive date   */  protected Path getPath(long time)  {    String formatString = getPathFormat();    if (formatString == null)      throw new IllegalStateException(L.l("getPath requires a format path"));        String pathString = getFormatName(formatString, time);    return getPwd().lookup(pathString);  }  /**   * Returns the name of the archived file   *   * @param time the archive date   */  protected Path getArchivePath(long time)  {    Path path = getPath();    String archiveFormat = getArchiveFormat();    String name = getFormatName(archiveFormat + _archiveSuffix, time);    Path newPath = path.getParent().lookup(name);    if (newPath.exists()) {      if (archiveFormat.indexOf("%H") < 0)	archiveFormat = archiveFormat + ".%H%M";      else if (archiveFormat.indexOf("%M") < 0)	archiveFormat = archiveFormat + ".%M";      for (int i = 0; i < 100; i++) {	String suffix;	if (i == 0)	  suffix = _archiveSuffix;	else	  suffix = "." + i + _archiveSuffix;		name = getFormatName(archiveFormat + suffix, time);	newPath = path.getParent().lookup(name);	if (! newPath.exists())	  break;      }    }    return newPath;  }  /**   * Returns the name of the archived file   *   * @param time the archive date   */  protected String getFormatName(String format, long time)  {    if (time <= 0)      time = Alarm.getCurrentTime();        if (format != null)      return _calendar.formatLocal(time, format);    else if (_rolloverCron != null)      return _rolloverPrefix + "." + _calendar.formatLocal(time, "%Y%m%d.%H");    else if (getRolloverPeriod() % (24 * 3600 * 1000L) == 0)      return _rolloverPrefix + "." + _calendar.formatLocal(time, "%Y%m%d");    else      return _rolloverPrefix + "." + _calendar.formatLocal(time, "%Y%m%d.%H");  }  /**   * error messages from the log itself   */  private void logInfo(String msg)  {    EnvironmentStream.logStderr(msg);  }  /**   * error messages from the log itself   */  private void logWarning(String msg, Throwable e)  {    EnvironmentStream.logStderr(msg, e);  }  /**   * Closes the log, flushing the results.   */  public synchronized void close()    throws IOException  {    closeLogStream();  }  /**   * Tries to close the log.   */  private void closeLogStream()  {    try {      WriteStream os = _os;      _os = null;      if (os != null)	os.close();    } catch (Throwable e) {      // can't log in log routines    }    try {      WriteStream zipOut = _zipOut;      _zipOut = null;      if (zipOut != null)	zipOut.close();    } catch (Throwable e) {      // can't log in log routines    }  }  private void flushTempStream()  {    TempStream ts = _tempStream;    _tempStream = null;    _tempStreamSize = 0;    try {      if (ts != null) {	if (_os == null)	  openLog();	try {	  ReadStream is = ts.openRead();	  try {	    is.writeToStream(_os);	  } finally {	    is.close();	  }	} catch (IOException e) {	  e.printStackTrace();	}      }    } finally {      notifyAll();    }  }  class ArchiveTask implements Runnable {    private boolean _isArchiving;        public void run()    {      try {	synchronized (this) {	  Path savedPath = _savedPath;	  	  if (savedPath != null)	    movePathToArchive(savedPath);	  	  _savedPath = null;	}      } finally {	// Write any new data from the temp stream to the log.	synchronized (AbstractRolloverLog.this) {	  _isRollingOver = false;	  flushTempStream();	}      }    }  }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?