// SaveLogs saves logs
332336
func (we *WorkflowExecutor) SaveLogs() (*wfv1.Artifact, error) {
	if we.Template.ArchiveLocation == nil || we.Template.ArchiveLocation.ArchiveLogs == nil || !*we.Template.ArchiveLocation.ArchiveLogs {
		return nil, nil
	}
	log.Infof("Saving logs")
	mainCtrID, err := we.GetMainContainerID()
	if err != nil {
		return nil, err
	}
	tempLogsDir := "/argo/outputs/logs"
	err = os.MkdirAll(tempLogsDir, os.ModePerm)
	if err != nil {
		return nil, errors.InternalWrapError(err)
	}
	fileName := "main.log"
	mainLog := path.Join(tempLogsDir, fileName)
	err = we.saveLogToFile(mainCtrID, mainLog)
	if err != nil {
		return nil, err
	}
	art := wfv1.Artifact{
		Name:             "main-logs",
		ArtifactLocation: *we.Template.ArchiveLocation,
	}
	if we.Template.ArchiveLocation.S3 != nil {
		shallowCopy := *we.Template.ArchiveLocation.S3
		art.S3 = &shallowCopy
		art.S3.Key = path.Join(art.S3.Key, fileName)
	} else if we.Template.ArchiveLocation.Artifactory != nil {
		shallowCopy := *we.Template.ArchiveLocation.Artifactory
		art.Artifactory = &shallowCopy
		artifactoryURL, urlParseErr := url.Parse(art.Artifactory.URL)
		if urlParseErr != nil {
			return nil, urlParseErr
		}
		artifactoryURL.Path = path.Join(artifactoryURL.Path, fileName)
		art.Artifactory.URL = artifactoryURL.String()
	} else if we.Template.ArchiveLocation.HDFS != nil {
		shallowCopy := *we.Template.ArchiveLocation.HDFS
		art.HDFS = &shallowCopy
		art.HDFS.Path = path.Join(art.HDFS.Path, fileName)
	} else {
		return nil, errors.Errorf(errors.CodeBadRequest, "Unable to determine path to store %s. Archive location provided no information", art.Name)
	}
	artDriver, err := we.InitDriver(art)
	if err != nil {
		return nil, err
	}
	err = artDriver.Save(mainLog, &art)
	if err != nil {
		return nil, err
	}

	return &art, nil
}
1182356
func (m *Mux) logFiles(app string) (map[string][]string, error) {
	files, err := ioutil.ReadDir(m.logDir)
	if err != nil {
		return nil, err
	}

	res := make(map[string][]string)
	for _, f := range files {
		n := f.Name()
		if f.IsDir() || !strings.HasSuffix(n, ".log") || !appIDPrefixPattern.MatchString(n) || !strings.HasPrefix(n, app) {
			continue
		}
		appID := n[:36]
		res[appID] = append(res[appID], filepath.Join(m.logDir, n))
	}

	return res, nil
}
490051
func WriteLogs(writer io.Writer, logs []*types.Log) {
	for _, log := range logs {
		fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex)

		for i, topic := range log.Topics {
			fmt.Fprintf(writer, "%08d  %x\n", i, topic)
		}

		fmt.Fprint(writer, hex.Dump(log.Data))
		fmt.Fprintln(writer)
	}
}
1125029
func AppLogs(appID string, lines int) error {
	c, appID, err := load(appID)

	if err != nil {
		return err
	}

	logs, err := apps.Logs(c, appID, lines)

	if err != nil {
		return err
	}

	return printLogs(logs)
}
1123375
func (s *agentLoggingStrategy) WriteLog(m params.LogRecord) error {
	level, _ := loggo.ParseLevel(m.Level)
	dbErr := errors.Annotate(s.dblogger.Log([]state.LogRecord{{
		Time:     m.Time,
		Entity:   s.entity,
		Version:  s.version,
		Module:   m.Module,
		Location: m.Location,
		Level:    level,
		Message:  m.Message,
	}}), "logging to DB failed")

	m.Entity = s.entity.String()
	fileErr := errors.Annotate(
		logToFile(s.fileLogger, s.filePrefix, m),
		"logging to logsink.log failed",
	)
	err := dbErr
	if err == nil {
		err = fileErr
	} else if fileErr != nil {
		err = errors.Errorf("%s; %s", dbErr, fileErr)
	}
	return err
}
1115252
func (a *api) ExportLogs(configParam ExportLogsConfig) (err error) {

	startTime := time.Now().UTC()
	// time.RFC3339 = "2006-01-02T15:04:05Z07:00"
	timeLabel := strings.Replace(startTime.Format(time.RFC3339), ":", "", -1)

	e := validateConfiguration(&configParam, timeLabel)
	if e != nil {
		return e
	}

	var exporter *logExporter
	defer func() {
		if exporter != nil {
			exporter.cleanup()
		}
	}()

	exporter, e = buildExporter(configParam, startTime, timeLabel, a.GetAllServiceDetails, a.GetHostMap)
	if e != nil {
		return e
	}

	numWarnings := 0
	foundIndexedDay := false

	log := log.WithFields(logrus.Fields{
		"tmpdir": exporter.tempdir,
		"from":   exporter.FromDate,
		"to":     exporter.ToDate,
	})
	log.Info("Starting part 1 of 3: Processing Logstash Elastic results")
	foundIndexedDay, numWarnings, e = exporter.retrieveLogs()
	if e != nil {
		return e
	} else if !foundIndexedDay {
		return fmt.Errorf("no logstash indexes exist for the given date range %s - %s", exporter.FromDate, exporter.ToDate)
	}

	log.WithFields(logrus.Fields{
		"numfiles": len(exporter.outputFiles),
	}).Info("Starting part 2 of 3: Sort output files")

	indexData := []string{}
	for i, outputFile := range exporter.outputFiles {
		if e := exporter.organizeAndGroomLogFile(i, numWarnings); e != nil {
			return e
		}
		indexData = append(indexData, exporter.fileIndex.GetFileIndexData(
			i,
			outputFile,
			exporter.getHostName(outputFile.HostID),
			exporter.getServiceName(outputFile.ServiceID)))
	}
	sort.Strings(indexData)

	servicesDesc := make([]string, 0)
	for _, id := range configParam.ServiceIDs {
		servicesDesc = append(servicesDesc, fmt.Sprintf("%s (%s)", exporter.getServiceName(id), id))
	}
	indexData = append([]string{
		"LOG EXPORT SUMMARY",
		fmt.Sprintf("       Export Ran On: %s", exporter.startTime.Format(time.RFC1123)),
		fmt.Sprintf("Available Date Range: %s - %s", exporter.days[len(exporter.days)-1], exporter.days[0]),
		fmt.Sprintf("     Requested Dates: %s - %s", configParam.FromDate, configParam.ToDate),
		fmt.Sprintf("      Exported Dates: %s - %s", exporter.minDateFound, exporter.maxDateFound),
		fmt.Sprintf("          Grouped By: %s", configParam.GroupBy),
		fmt.Sprintf("Requested Service(s): %s", strings.Join(servicesDesc, ", ")),
		fmt.Sprintf("Child Svcs Excluded?: %s", strconv.FormatBool(configParam.ExcludeChildren)),
		fmt.Sprintf("   Requested File(s): %s", strings.Join(configParam.FileNames, ", ")),
		"",
		"INDEX OF LOG FILES",
		exporter.fileIndex.GetIndexHeader()},
		indexData...)
	indexData = append(indexData, "")
	indexFile := filepath.Join(exporter.tempdir, "index.txt")
	e = ioutil.WriteFile(indexFile, []byte(strings.Join(indexData, "\n")), 0644)
	if e != nil {
		return fmt.Errorf("failed writing to %s: %s", indexFile, e)
	}

	log.WithFields(logrus.Fields{
		"outfile": exporter.OutFileName,
	}).Info("Starting part 3 of 3: Generate tar file")
	gz := gzip.NewWriter(exporter.outFile)
	defer gz.Close()
	tarfile := tar.NewWriter(gz)
	defer tarfile.Close()
	if e := volume.ExportDirectory(tarfile, exporter.tempdir, filepath.Base(exporter.tempdir)); e != nil {
		return fmt.Errorf("failed to write tgz %s: %s", exporter.OutFileName, e)
	}

	if numWarnings != 0 {
		log.WithFields(logrus.Fields{
			"warnfile": filepath.Join(filepath.Base(exporter.tempdir), filepath.Base(exporter.parseWarningsFilename)),
		}).Info("Warnings for log parse are included in the tar file")
	}

	return nil
}
551404
func InitLogs() {
	log.SetOutput(KlogWriter{})
	log.SetFlags(0)
	// The default glog flush interval is 5 seconds.
	go wait.Forever(klog.Flush, *logFlushFreq)
}
1195798
func (fsm *SimpleFSM) Logs() [][]byte {
	fsm.mu.Lock()
	defer fsm.mu.Unlock()
	copied := make([][]byte, len(fsm.logs))
	copy(copied, fsm.logs)
	return copied
}
900903
func (l *DefaultLogger) Log(level int, msg string, args []interface{}) {
	// log if the log level (warn=4) >= level of message (err=3)
	if l.level < level || silent {
		return
	}
	l.formatter.Format(l.writer, level, msg, args)
}
1209431
func saveConfigs(configModel ConfigsModel) error {
	if err := ensureEnvmanConfigDirExists(); err != nil {
		return err
	}

	bytes, err := json.Marshal(configModel)
	if err != nil {
		return err
	}
	configsPth := getEnvmanConfigsFilePath()
	return fileutil.WriteBytesToFile(configsPth, bytes)
}
714022
func (m *MockServiceAPIClient) ServiceLogs(ctx context.Context, serviceID string, options types.ContainerLogsOptions) (io.ReadCloser, error) {
	ret := m.ctrl.Call(m, "ServiceLogs", ctx, serviceID, options)
	ret0, _ := ret[0].(io.ReadCloser)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
563031
func (as *AnalyticalStorage) FindLogs(ctx context.Context, filter influxdb.LogFilter) ([]*influxdb.Log, int, error) {
	var logs []*influxdb.Log
	if filter.Run != nil {
		run, err := as.FindRunByID(ctx, filter.Task, *filter.Run)
		if err != nil {
			return nil, 0, err
		}
		for i := 0; i < len(run.Log); i++ {
			logs = append(logs, &run.Log[i])
		}
		return logs, len(logs), nil
	}

	// add historical logs to the transactional logs.
	runs, n, err := as.FindRuns(ctx, influxdb.RunFilter{Task: filter.Task})
	if err != nil {
		return nil, 0, err
	}

	for _, run := range runs {
		for i := 0; i < len(run.Log); i++ {
			logs = append(logs, &run.Log[i])
		}
	}

	return logs, n, err
}
1300651
func (s *syncLogStore) StoreLog(log *raft.Log) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.store.StoreLog(log)
}
728516
func (l *Ledis) StoreLogsFromData(data []byte) error {
	rb := bytes.NewReader(data)

	return l.StoreLogsFromReader(rb)
}
1203477
func (uow *UnitOfWork) Logs(follow bool, timestamps bool, tail string, colorize bool, since string) {
	uow.Targeted().Logs(follow, timestamps, tail, colorize, since)
}
1213756
func (b *FastLogStore) StoreLogs(logs []*raft.Log) error {
	b.mu.Lock()
	defer b.mu.Unlock()
	if b.closed {
		return ErrClosed
	}
	if b.persist {
		var num = make([]byte, 8)
		b.buf = b.buf[:0]
		b.buf = append(b.buf, cmdStoreLogs)
		binary.LittleEndian.PutUint64(num, uint64(len(logs)))
		b.buf = append(b.buf, num...)
		for _, log := range logs {
			b.buf = bufferLog(b.buf, log)
		}
		if err := b.writeBuf(); err != nil {
			return err
		}
	}
	for _, log := range logs {
		b.lvm[log.Index] = log
		if b.limits {
			if b.min == 0 {
				b.min, b.max = log.Index, log.Index
			} else if log.Index < b.min {
				b.min = log.Index
			} else if log.Index > b.max {
				b.max = log.Index
			}
		}
	}
	return nil
}
105204
func (e *EncryptedRaftLogger) SaveEntries(st raftpb.HardState, entries []raftpb.Entry) error {
	e.encoderMu.RLock()
	defer e.encoderMu.RUnlock()

	if e.wal == nil {
		return fmt.Errorf("raft WAL has either been closed or has never been created")
	}
	return e.wal.Save(st, entries)
}