// Mark an event happening, using given timestamp.
//
// The implementation assumes time is monotonic, the behaviour is undefined in
// the case of time going back. This operation has logarithmic complexity.
551253
func (ss *Rate) Touch(key string, nowTs time.Time) {
	now := nowTs.UnixNano()

	var bucket *bucket
	if bucketno, found := ss.keytobucketno[key]; found {
		bucket = &ss.buckets[bucketno]
	} else {
		bucketno = uint32(ss.sh.h[0])

		bucket = &ss.buckets[bucketno]
		delete(ss.keytobucketno, bucket.key)
		ss.keytobucketno[key] = bucketno

		bucket.key, bucket.errLastTs, bucket.errRate =
			key, bucket.lastTs, bucket.rate
	}

	if bucket.lastTs != 0 {
		bucket.rate = ss.count(bucket.rate, bucket.lastTs, now)
	}
	bucket.lastTs = now

	// Even lastTs change may change ordering.
	heap.Fix(&ss.sh, int(bucket.idx))
}
374177
func (c *ChatUpdateCall) Timestamp(timestamp string) *ChatUpdateCall {
	c.timestamp = timestamp
	return c
}
1018462
func (b *BufferedLogger) Log(in []state.LogRecord) error {
	b.mu.Lock()
	defer b.mu.Unlock()
	for len(in) > 0 {
		r := cap(b.buf) - len(b.buf)
		n := len(in)
		if n > r {
			n = r
		}
		b.buf = append(b.buf, in[:n]...)
		in = in[n:]
		if len(b.buf) >= cap(b.buf) {
			if err := b.flush(); err != nil {
				return errors.Trace(err)
			}
		}
	}
	if len(b.buf) > 0 && b.flushTimer == nil {
		b.flushTimer = b.clock.AfterFunc(b.flushInterval, b.flushOnTimer)
	}
	return nil
}
204891
func TimeTrack(start time.Time, name string) {
	elapsed := time.Since(start)
	log.Printf("%s took %s", name, elapsed)
}
652129
func (handler *Handler) Event(logEvent *event.Event) error {
	handler.mutex.Lock()
	handler.events = append(handler.events, logEvent)
	handler.mutex.Unlock()
	return nil
}
140935
func (s *Snapshotter) stream() {
	clockTicker := time.NewTicker(clockUpdateInterval)
	defer clockTicker.Stop()

	// flushEvent is used to handle writing out an event
	flushEvent := func(e Event) {
		// Stop recording events after a leave is issued
		if s.leaving {
			return
		}
		switch typed := e.(type) {
		case MemberEvent:
			s.processMemberEvent(typed)
		case UserEvent:
			s.processUserEvent(typed)
		case *Query:
			s.processQuery(typed)
		default:
			s.logger.Printf("[ERR] serf: Unknown event to snapshot: %#v", e)
		}
	}

	for {
		select {
		case <-s.leaveCh:
			s.leaving = true

			// If we plan to re-join, keep our state
			if !s.rejoinAfterLeave {
				s.aliveNodes = make(map[string]string)
			}
			s.tryAppend("leave\n")
			if err := s.buffered.Flush(); err != nil {
				s.logger.Printf("[ERR] serf: failed to flush leave to snapshot: %v", err)
			}
			if err := s.fh.Sync(); err != nil {
				s.logger.Printf("[ERR] serf: failed to sync leave to snapshot: %v", err)
			}

		case e := <-s.streamCh:
			flushEvent(e)

		case <-clockTicker.C:
			s.updateClock()

		case <-s.shutdownCh:
			// Setup a timeout
			flushTimeout := time.After(shutdownFlushTimeout)

			// Snapshot the clock
			s.updateClock()

			// Clear out the buffers
		FLUSH:
			for {
				select {
				case e := <-s.streamCh:
					flushEvent(e)
				case <-flushTimeout:
					break FLUSH
				default:
					break FLUSH
				}
			}

			if err := s.buffered.Flush(); err != nil {
				s.logger.Printf("[ERR] serf: failed to flush snapshot: %v", err)
			}
			if err := s.fh.Sync(); err != nil {
				s.logger.Printf("[ERR] serf: failed to sync snapshot: %v", err)
			}
			s.fh.Close()
			close(s.waitCh)
			return
		}
	}
}
75150
func Time(timeFormat string) Formatter {
	return func(buffer Buffer, event *cue.Event) {
		buffer.AppendString(event.Time.Format(timeFormat))
	}
}
1291254
func (m *Message) setTimestamp(s string) {
	if m.Timestamp == "" {
		m.Timestamp = s
	}
}
1180523
func (c Context) Timestamp() Context {
	c.l = c.l.Hook(th)
	return c
}
608174
func (m *Metrics) AddEvent(e *log.Event, outlier bool) {

	for metric, val := range e.TimeMetrics {
		stats, seenMetric := m.TimeMetrics[metric]
		if !seenMetric {
			m.TimeMetrics[metric] = &TimeStats{
				vals: []float64{},
			}
			stats = m.TimeMetrics[metric]
		}
		if outlier {
			stats.outlierSum += val
		} else {
			stats.Sum += val
		}
		stats.vals = append(stats.vals, float64(val))
	}

	for metric, val := range e.NumberMetrics {
		stats, seenMetric := m.NumberMetrics[metric]
		if !seenMetric {
			m.NumberMetrics[metric] = &NumberStats{
				vals: []uint64{},
			}
			stats = m.NumberMetrics[metric]
		}
		if outlier {
			stats.outlierSum += val
		} else {
			stats.Sum += val
		}
		stats.vals = append(stats.vals, val)
	}

	for metric, val := range e.BoolMetrics {
		stats, seenMetric := m.BoolMetrics[metric]
		if !seenMetric {
			stats = &BoolStats{}
			m.BoolMetrics[metric] = stats
		}
		if val {
			if outlier {
				stats.outlierSum += 1
			} else {
				stats.Sum += 1
			}
		}
	}
}
1267971
func Mark(format string, args ...interface{}) func() {
	if !debug {
		return func() {}
	}

	Trace("START "+format, args...)
	old := logger.Prefix()
	logger.SetPrefix(old + "|    ")
	return func() {
		logger.SetPrefix(old)
		Trace("END "+format, args...)
	}
}
772621
func createEvent(action string) *Event {
	return &Event{
		ID:        uuid.Generate().String(),
		Timestamp: time.Now(),
		Action:    action,
	}
}
349156
func (e *Listener) Event(event *core.Event) {
	openlogging.GetLogger().Info(event.Key)
	openlogging.GetLogger().Infof(fmt.Sprintf("%s", event.Value))
	openlogging.GetLogger().Info(event.EventType)
}
598262
func (h *TextHandler) Log(logger_name string, level LogLevel, msg string,
	calldepth int) {
	h.mtx.RLock()
	output, template := h.output, h.template
	h.mtx.RUnlock()
	event := LogEvent{
		LoggerName: logger_name,
		Level:      level,
		Message:    strings.TrimRight(msg, "\n\r"),
		Timestamp:  time.Now()}
	if calldepth >= 0 {
		_, event.Filepath, event.Line, _ = runtime.Caller(calldepth + 1)
	}
	var buf bytes.Buffer
	err := template.Execute(&buf, &event)
	if err != nil {
		output.Output(level, []byte(
			fmt.Sprintf("log format template failed: %s", err)))
		return
	}
	output.Output(level, buf.Bytes())
}
1011778
func (p *Parser) handleEvent(rawEvent []string) *event.Event {
	normalizer := normalizer.Parser{}
	if len(rawEvent) == 0 {
		return nil
	}
	firstLine := rawEvent[0]

	// First, try to parse the prefix
	match, suffix, generalMeta := parsePrefix(p.pgPrefixRegex, firstLine)
	if !match {
		// Note: this may be noisy when debug logging is turned on, since the
		// postgres general log contains lots of other statements as well.
		logrus.WithField("line", firstLine).Debug("Log line prefix didn't match expected format")
		return nil
	}

	ev := &event.Event{
		Data: make(map[string]interface{}, 0),
	}

	addFieldsToEvent(generalMeta, ev)

	// Now, parse the slow query header
	match, query, slowQueryMeta := parsePrefix(slowQueryHeaderRegex, suffix)

	if !match {
		logrus.WithField("line", firstLine).Debug("didn't find slow query header, skipping line")
		return nil
	}

	if rawDuration, ok := slowQueryMeta["duration"]; ok {
		duration, _ := strconv.ParseFloat(rawDuration, 64)
		ev.Data["duration"] = duration
	} else {
		logrus.WithField("query", query).Debug("Failed to find query duration in log line")
	}

	// Finally, concatenate the remaining text to form the query, and attempt to
	// normalize it.
	for _, line := range rawEvent[1:] {
		query += " " + strings.TrimLeft(line, " \t")
	}
	normalizedQuery := normalizer.NormalizeQuery(query)

	ev.Data["query"] = query
	ev.Data["normalized_query"] = normalizedQuery
	if len(normalizer.LastTables) > 0 {
		ev.Data["tables"] = strings.Join(normalizer.LastTables, " ")
	}
	if len(normalizer.LastComments) > 0 {
		ev.Data["comments"] = "/* " + strings.Join(normalizer.LastComments, " */ /* ") + " */"
	}

	return ev
}
1111551
func (logTags) Timestamp(ts time.Time) LogTag {
	return func(lr *LogRecord) {
		lr.Timestamp = ts.UTC().Format(time.RFC3339Nano)
	}
}
39183
func PgXactCommitTimestamp(db XODB, v0 pgtypes.Xid) (time.Time, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.pg_xact_commit_timestamp($1)`

	// run query
	var ret time.Time
	XOLog(sqlstr, v0)
	err = db.QueryRow(sqlstr, v0).Scan(&ret)
	if err != nil {
		return time.Time{}, err
	}

	return ret, nil
}