Appends a logging event.

If the target file changes because of passage of time (e.g. at midnight)
the current file is closed. A new file, with the new date, will be
opened by the write() method.
430270
public function append(\n2n\log4php\logging\LoggingEvent $event) {
		$eventDate = $this->getDate($event->getTimestamp());
		
		// Initial setting of current date
		if (!isset($this->currentDate)) {
			$this->currentDate = $eventDate;
		} 
		
		// Check if rollover is needed
		else if ($this->currentDate !== $eventDate) {
			$this->currentDate = $eventDate;
			
			// Close the file if it's open.
			// Note: $this->close() is not called here because it would set
			//       $this->closed to true and the appender would not recieve
			//       any more logging requests
			if (is_resource($this->fp)) {
				$this->write($this->layout->getFooter());
				fclose($this->fp);
			}
			$this->fp = null;
		}
	
		parent::append($event);
	}
171819
def _log_to_file(self, etype, source, msg='', target='', hostmask='', params=''):
        
        today = datetime.utcnow()
        # TODO: Use self.locale['timezone'] for changing time
        date = today.strftime(self.locale['date_fmt'])
        time = today.strftime(self.locale['time_fmt'])
        datetime_s = today.strftime(self.locale['short_datetime_fmt'])
        datetime_l = today.strftime(self.locale['long_datetime_fmt'])
        
        if target == self.nickname and etype in ('privmsg', 'action'):
            target = source

        if etype in self.log_formats:
            file_path = os.path.expanduser(self.log_file.format(**locals()))
            file_dir = os.path.dirname(file_path)
            if not os.path.isdir(file_dir):
                os.makedirs(file_dir)

            line = self.log_formats[etype].format(**locals())
            with open(file_path, 'a') as log:
                log.write(line+'\n')
841937
public void appendLine(String target, long nowTime) throws IOException
    {
        if (this.nextSwitchTime <= nowTime)
        {
            switchWriter(nowTime);
        }

        this.currentWriter.appendLine(target);
    }
204121
public static void append(Path self, byte[] bytes) throws IOException {
        OutputStream stream = null;
        try {
            stream = Files.newOutputStream(self, CREATE, APPEND);
            stream.write(bytes, 0, bytes.length);
            stream.flush();

            OutputStream temp = stream;
            stream = null;
            temp.close();
        } finally {
            closeWithWarning(stream);
        }
    }
714052
public void flush2file() {
        StringBuffer filename = new StringBuffer();
        {
            Calendar now = Calendar.getInstance();
            filename.append(now.get(Calendar.YEAR));
            int month = now.get(Calendar.MONTH) + 1;
            filename.append((month < 10 ? "0" : "") + month);
            int day = now.get(Calendar.DAY_OF_MONTH);
            filename.append((day < 10 ? "0" : "") + day);
            int militaryHour = now.get(Calendar.HOUR_OF_DAY);
            filename
                    .append("-" + (militaryHour < 10 ? "0" : "") + militaryHour);
            int minute = now.get(Calendar.MINUTE);
            filename.append((minute < 10 ? "0" : "") + minute);
            int second = now.get(Calendar.SECOND);
            filename.append((second < 10 ? "0" : "") + second);
            int milliseconds = now.get(Calendar.MILLISECOND);
            filename
                    .append("-"
                            + (milliseconds < 10 ? "00"
                                    : milliseconds < 100 ? "0" : "")
                            + milliseconds);
            filename.append(".txt");
        }
        try {
            File file = new File(directoryPath, filename.toString());
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            PrintStream userLog = new PrintStream(fileOutputStream);
            userLog.print(jTextArea.getText());
            userLog.close();
        } catch (FileNotFoundException e) {
            jTextArea.append("COULD NOT WRITE PROCESSING REPORT TO FILE!!!\n");
        }
    }
1317211
public void addAppenderEvent(final Category cat, final Appender appender) {

		updateDefaultLayout(appender);

		if (appender instanceof FoundationFileRollingAppender) {
			final FoundationFileRollingAppender timeSizeRollingAppender = (FoundationFileRollingAppender) appender;

			// update the appender with default vales such as logging pattern, file size etc.
			//updateDefaultTimeAndSizeRollingAppender(timeSizeRollingAppender);

			// read teh proeprties and determine if archiving should be enabled.
			updateArchivingSupport(timeSizeRollingAppender);

			// by default add the rolling file listener to enable application
			// state.
			timeSizeRollingAppender.setFileRollEventListener(FoundationRollEventListener.class.getName());

			boolean rollOnStartup = true;

			if (FoundationLogger.log4jConfigProps != null && FoundationLogger.log4jConfigProps.containsKey(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString())) {
				rollOnStartup = Boolean.valueOf(FoundationLogger.log4jConfigProps.getProperty(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString()));
			}

			timeSizeRollingAppender.setRollOnStartup(rollOnStartup);

			// refresh the appender
			timeSizeRollingAppender.activateOptions();

			
		//	timeSizeRollingAppender.setOriginalLayout(); //So application state will not make any problems

		}else if(!(appender instanceof FoundationFileRollingAppender) && (appender instanceof TimeAndSizeRollingAppender)){ //TimeAndSizeRollingAppender
			final TimeAndSizeRollingAppender timeSizeRollingAppender = (TimeAndSizeRollingAppender) appender;

			// update the appender with default vales such as logging pattern, file size etc.
			updateDefaultTimeAndSizeRollingAppender(timeSizeRollingAppender);

			// read teh proeprties and determine if archiving should be enabled.
			updateArchivingSupport(timeSizeRollingAppender);

			// by default add the rolling file listener to enable application
			// state.
			timeSizeRollingAppender.setFileRollEventListener(FoundationRollEventListener.class.getName());

			boolean rollOnStartup = true;

			if (FoundationLogger.log4jConfigProps != null && FoundationLogger.log4jConfigProps.containsKey(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString())) {
				rollOnStartup = Boolean.valueOf(FoundationLogger.log4jConfigProps.getProperty(FoundationLoggerConstants.Foundation_ROLL_ON_STARTUP.toString()));
			}

			timeSizeRollingAppender.setRollOnStartup(rollOnStartup);

			// refresh the appender
			timeSizeRollingAppender.activateOptions();

			
		//	timeSizeRollingAppender.setOriginalLayout();
		}
		if ( ! (appender instanceof org.apache.log4j.AsyncAppender))
            initiateAsyncSupport(appender);

	}
646050
def record_event(self, event):
        
        with open(self._path, 'a') as file_:
            file_.write(str(event) + '\n')
374952
private String write(String logDir) throws IOException, ExecutionException, InterruptedException {
        final File file = new File(logDir, "trace_" + System.currentTimeMillis() + ".json.gz");
        if (file.exists()) {
            throw new IOException("Trace file " + file.getAbsolutePath() + " already exists");
        }
        if (!file.getParentFile().canWrite() || !file.getParentFile().canExecute()) {
            throw new IOException("Trace file " + file.getAbsolutePath() + " is not writable");
        }

        SettableFuture<Future<?>> f = SettableFuture.create();
        m_work.offer(() -> f.set(dumpEvents(file)));
        final Future<?> writeFuture = f.get();
        if (writeFuture != null) {
            writeFuture.get(); // Wait for the write to finish without blocking new events
            return file.getAbsolutePath();
        } else {
            // A write is already in progress, ignore this request
            return null;
        }
    }
1245867
def on_created(self, event):
        
        logger.debug("file created: %s", event.src_path)
        if not event.is_directory:
            self.update_file(event.src_path)
136810
function writeChangelog(changelog) {
      var fileContents = null;
      var firstLineFile = null;
      var firstLineFileHeader = null;
      var regex = null;

      if (options.insertType && grunt.file.exists(options.dest)) {
        fileContents = grunt.file.read(options.dest);
        firstLineFile = fileContents.split('\n')[0];
        grunt.log.debug('firstLineFile = ' + firstLineFile);

        switch (options.insertType) {
          case 'prepend':
            changelog = changelog + '\n' + fileContents;
            break;
          case 'append':
            changelog = fileContents + '\n' + changelog;
            break;
          default:
            grunt.fatal('"' + options.insertType + '" is not a valid insertType. Please use "append" or "prepend".');
            return false;
        }
      }

      if (options.fileHeader) {
        firstLineFileHeader = options.fileHeader.split('\n')[0];
        grunt.log.debug('firstLineFileHeader = ' + firstLineFileHeader);

        if (options.insertType === 'prepend') {
          if (firstLineFile !== firstLineFileHeader) {
            changelog = options.fileHeader + '\n\n' + changelog;
          } else {
            regex = new RegExp(options.fileHeader+'\n\n','m');
            changelog = options.fileHeader + '\n\n' + changelog.replace(regex, '');
          }

        // insertType === 'append' || undefined
        } else {
          if (firstLineFile !== firstLineFileHeader) {
            changelog = options.fileHeader + '\n\n' + changelog;
          }
        }

      }


      grunt.file.write(options.dest, changelog);

      // Log the results.
      grunt.log.ok(changelog);
      grunt.log.writeln();
      grunt.log.writeln('Changelog created at '+ options.dest.toString().cyan + '.');
    }
721283
public synchronized void writeHeader(long timestamp) throws IOException {
		if (writer == null && headerBytes != null) {
			writer = createNewWriter(manager.startNewFile(timestamp));
			writer.write(headerBytes);
			manager.notifyOfFileAction(LogEventListener.EVENTTYPEROLL) ;
		}
	}
300273
def _append_date(self, value, _file):
        
        _tabs = '\t' * self._tctr
        _text = value.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
        _labs = '{tabs}<date>{text}</date>\n'.format(tabs=_tabs, text=_text)
        _file.write(_labs)
754261
@Override
  protected void subAppend(LoggingEvent event) {
    super.subAppend(event);
    // That should've gone into our writer. Notify the LogContext.
    String logOutput = writer.toString();
    writer.reset();

    OperationLog log = operationManager.getOperationLogByThread();
    if (log == null) {
      LOG.debug(" ---+++=== Dropped log event from thread " + event.getThreadName());
      return;
    }
    log.writeOperationLog(logOutput);
  }
1213253
private void performNextWrite() {
        Append append = getNextAppend();
        if (append == null) {
            return;
        }
        long traceId = LoggerHelpers.traceEnter(log, "storeAppend", append);
        Timer timer = new Timer();
        storeAppend(append)
                .whenComplete((v, e) -> {
                    handleAppendResult(append, e, timer);
                    LoggerHelpers.traceLeave(log, "storeAppend", traceId, v, e);
                })
                .whenComplete((v, e) -> append.getData().release());
    }
227430
function (onDone) {

		// refuse any write or log creation
		l_logLock = true;

		//console.log(l_name + '::disposeAllLogs::waitClosing...');
		console.log(l_name + '::disposeAllLogs::closing ' + Object.keys(l_logs).length + ' log files...');

		l_onAllClosed = onDone;

		if (l_checkDoneBusy === false) {
			l_checkDoneBusy = true;
			l_checkLogClose();
		}
	}
334059
def _append(self, ev_type: Enum, data: ActionLogData) -> None:
        
        event = ActionLogEvent(None, ev_type, data, types=self._event_types)
        with open(self._file_path, mode='a+', newline='') as f:
            f.write(event.pack(delimiter=self._delimiter))
        self._items.append(event)
454476
def _write_log(self, log_type, log_time, message):
        
        timestamp = datetime.datetime.now().strftime(" %Y-%m-%d %H:%M:%S")
        log_entry = "[{}{}] {}".format(log_type, timestamp if log_time else "", message)
        if self._logger and callable(getattr(self._logger, self._logger_methods[log_type], None)):
            # Check for log handler (sends message only if _logger_no_prefix is True)
            getattr(
                self._logger,
                self._logger_methods[log_type],
                None
                )(message if self._logger_no_prefix else log_entry)
        elif self._log_file:
            # Otherwise write to file, if a file has been specified
            with open(self._log_file, 'a') as logfile:
                try:
                    logfile.write(unicode(log_entry + "\n"))
                except NameError: # `unicode` only works in Python 2
                    logfile.write(log_entry + "\n")
        else:
            # Otherwise, print to STDOUT
            print(log_entry)