// Prints logs for workflow pod steps and return most recent log timestamp per pod name
173807
func (p *logPrinter) printRecentWorkflowLogs(wf *v1alpha1.Workflow) map[string]*time.Time {
	var podNodes []v1alpha1.NodeStatus
	err := util.DecompressWorkflow(wf)
	if err != nil {
		log.Warn(err)
		return nil
	}
	for _, node := range wf.Status.Nodes {
		if node.Type == v1alpha1.NodeTypePod && node.Phase != v1alpha1.NodeError {
			podNodes = append(podNodes, node)
		}
	}
	var logs [][]logEntry
	var wg sync.WaitGroup
	wg.Add(len(podNodes))
	var mux sync.Mutex

	for i := range podNodes {
		node := podNodes[i]
		go func() {
			defer wg.Done()
			var podLogs []logEntry
			err := p.getPodLogs(context.Background(), getDisplayName(node), node.ID, wf.Namespace, false, p.tail, p.sinceSeconds, p.sinceTime, func(entry logEntry) {
				podLogs = append(podLogs, entry)
			})

			if err != nil {
				log.Warn(err)
				return
			}

			mux.Lock()
			logs = append(logs, podLogs)
			mux.Unlock()
		}()

	}
	wg.Wait()

	flattenLogs := mergeSorted(logs)

	if p.tail != nil {
		tail := *p.tail
		if int64(len(flattenLogs)) < tail {
			tail = int64(len(flattenLogs))
		}
		flattenLogs = flattenLogs[0:tail]
	}
	timeByPod := make(map[string]*time.Time)
	for _, entry := range flattenLogs {
		p.printLogEntry(entry)
		timeByPod[entry.pod] = &entry.time
	}
	return timeByPod
}
607830
func (pub *Impl) ProbeLogs() {
	wg := new(sync.WaitGroup)
	for _, log := range pub.ctLogsCache.LogURIs() {
		wg.Add(1)
		go func(uri string) {
			defer wg.Done()
			c := http.Client{
				Timeout: time.Minute*2 + time.Second*30,
			}
			url, err := url.Parse(uri)
			if err != nil {
				pub.log.Errf("failed to parse log URI: %s", err)
			}
			url.Path = ct.GetSTHPath
			s := time.Now()
			resp, err := c.Get(url.String())
			took := time.Since(s).Seconds()
			var status string
			if err == nil {
				defer func() { _ = resp.Body.Close() }()
				status = resp.Status
			} else {
				status = "error"
			}
			pub.metrics.probeLatency.With(prometheus.Labels{
				"log":    uri,
				"status": status,
			}).Observe(took)
		}(log)
	}
	wg.Wait()
}
32358
func PrintRunningStepHeader(stepInfo stepmanModels.StepInfoModel, step stepmanModels.StepModel, idx int) {
	sep := fmt.Sprintf("+%s+", strings.Repeat("-", stepRunSummaryBoxWidthInChars-2))

	fmt.Println(sep)
	fmt.Println(getRunningStepHeaderMainSection(stepInfo, idx))
	fmt.Println(sep)
	fmt.Println(getRunningStepHeaderSubSection(step, stepInfo))
	fmt.Println(sep)
	fmt.Println("|" + strings.Repeat(" ", stepRunSummaryBoxWidthInChars-2) + "|")
}
158249
func (vm *VirtualMachine) logPrintf(format string, v ...interface{}) {
	f, err := os.OpenFile(vm.log, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0)
	if err != nil {
		log.Println(err)
		return
	}
	log.New(f, "vmx ", log.Flags()).Printf(format, v...)
	_ = f.Close()
}
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
}
353565
func (flag *OutputFlag) Log(s string) (int, error) {
	if len(s) > 0 && s[0] == '\r' {
		flag.Write([]byte{'\r', 033, '[', 'K'})
		s = s[1:]
	}

	return flag.WriteString(time.Now().Format("[02-01-06 15:04:05] ") + s)
}
212844
func EnvmanJSONPrint(envstorePth string) (string, error) {
	logLevel := log.GetLevel().String()
	args := []string{"--loglevel", logLevel, "--path", envstorePth, "print", "--format", "json", "--expand"}

	var outBuffer bytes.Buffer
	var errBuffer bytes.Buffer

	if err := command.RunCommandWithWriters(io.Writer(&outBuffer), io.Writer(&errBuffer), "envman", args...); err != nil {
		return outBuffer.String(), fmt.Errorf("Error: %s, details: %s", err, errBuffer.String())
	}

	return outBuffer.String(), nil
}
1203477
func (uow *UnitOfWork) Logs(follow bool, timestamps bool, tail string, colorize bool, since string) {
	uow.Targeted().Logs(follow, timestamps, tail, colorize, since)
}
195571
func (d *dockerService) GetContainerLogs(_ context.Context, pod *v1.Pod, containerID kubecontainer.ContainerID, logOptions *v1.PodLogOptions, stdout, stderr io.Writer) error {
	container, err := d.client.InspectContainer(containerID.ID)
	if err != nil {
		return err
	}

	var since int64
	if logOptions.SinceSeconds != nil {
		t := metav1.Now().Add(-time.Duration(*logOptions.SinceSeconds) * time.Second)
		since = t.Unix()
	}
	if logOptions.SinceTime != nil {
		since = logOptions.SinceTime.Unix()
	}
	opts := dockertypes.ContainerLogsOptions{
		ShowStdout: true,
		ShowStderr: true,
		Since:      strconv.FormatInt(since, 10),
		Timestamps: logOptions.Timestamps,
		Follow:     logOptions.Follow,
	}
	if logOptions.TailLines != nil {
		opts.Tail = strconv.FormatInt(*logOptions.TailLines, 10)
	}

	sopts := libdocker.StreamOptions{
		OutputStream: stdout,
		ErrorStream:  stderr,
		RawTerminal:  container.Config.Tty,
	}
	return d.client.Logs(containerID.ID, opts, sopts)
}
465492
func (we *WorkflowExecutor) AnnotateOutputs(logArt *wfv1.Artifact) error {
	outputs := we.Template.Outputs.DeepCopy()
	if logArt != nil {
		outputs.Artifacts = append(outputs.Artifacts, *logArt)
	}

	if !outputs.HasOutputs() {
		return nil
	}
	log.Infof("Annotating pod with output")
	outputBytes, err := json.Marshal(outputs)
	if err != nil {
		return errors.InternalWrapError(err)
	}
	return we.AddAnnotation(common.AnnotationKeyOutputs, string(outputBytes))
}
978103
func (l *DistinctLogger) Printf(format string, v ...interface{}) {
	logStatement := fmt.Sprintf(format, v...)
	l.print(logStatement)
}
834643
func printStatus(p *pkgPod.Pod) error {
	if flagFormat != outputFormatTabbed {
		pod, err := lib.NewPodFromInternalPod(p)
		if err != nil {
			return fmt.Errorf("error converting pod: %v", err)
		}
		switch flagFormat {
		case outputFormatJSON:
			result, err := json.Marshal(pod)
			if err != nil {
				return fmt.Errorf("error marshaling the pod: %v", err)
			}
			stdout.Print(string(result))
		case outputFormatPrettyJSON:
			result, err := json.MarshalIndent(pod, "", "\t")
			if err != nil {
				return fmt.Errorf("error marshaling the pod: %v", err)
			}
			stdout.Print(string(result))
		}
		return nil
	}

	state := p.State()
	stdout.Printf("state=%s", state)

	created, err := p.CreationTime()
	if err != nil {
		return fmt.Errorf("unable to get creation time for pod %q: %v", p.UUID, err)
	}
	createdStr := created.Format(defaultTimeLayout)

	stdout.Printf("created=%s", createdStr)

	started, err := p.StartTime()
	if err != nil {
		return fmt.Errorf("unable to get start time for pod %q: %v", p.UUID, err)
	}
	var startedStr string
	if !started.IsZero() {
		startedStr = started.Format(defaultTimeLayout)
		stdout.Printf("started=%s", startedStr)
	}

	if state == pkgPod.Running || state == pkgPod.Exited {
		stdout.Printf("networks=%s", fmtNets(p.Nets))
	}

	if !(state == pkgPod.Running || state == pkgPod.Deleting || state == pkgPod.ExitedDeleting || state == pkgPod.Exited || state == pkgPod.ExitedGarbage) {
		return nil
	}

	if pid, err := p.Pid(); err == nil {
		// the pid file might not be written yet when the state changes to 'Running'
		// it may also never be written if systemd never executes (e.g.: a bad command)
		stdout.Printf("pid=%d", pid)
	}
	stdout.Printf("exited=%t", (state == pkgPod.Exited || state == pkgPod.ExitedGarbage))

	if state != pkgPod.Running {
		stats, err := getExitStatuses(p)
		if err != nil {
			return fmt.Errorf("unable to get exit statuses for pod %q: %v", p.UUID, err)
		}
		for app, stat := range stats {
			stdout.Printf("app-%s=%d", app, stat)
		}
	}
	return nil
}
182630
func PrintFilesOrFail(files []string, err error) {
	FailOnError(err)
	fmt.Println(strings.Join(files, "\n"))
}
1047644
func (f *FakeDockerClient) Logs(id string, opts dockertypes.ContainerLogsOptions, sopts StreamOptions) error {
	f.Lock()
	defer f.Unlock()
	f.appendCalled(CalledDetail{name: "logs"})
	return f.popError("logs")
}
167348
func (p *printer) steps(steps []*pb.Step) {
	maxNameWidth := 0
	for _, s := range steps {
		if w := utf8.RuneCountInString(s.Name); w > maxNameWidth {
			maxNameWidth = w
		}
	}

	for _, s := range steps {
		p.f("%sStep ", ansiStatus[s.Status])
		p.fw(maxNameWidth+5, "%q", s.Name)
		p.fw(10, "%s", s.Status)

		// Print duration.
		durString := ""
		if start, err := ptypes.Timestamp(s.StartTime); err == nil {
			var stepDur time.Duration
			if end, err := ptypes.Timestamp(s.EndTime); err == nil {
				stepDur = end.Sub(start)
			} else {
				now := p.nowFn()
				stepDur = now.Sub(start.In(now.Location()))
			}
			durString = truncateDuration(stepDur).String()
		}
		p.fw(10, "%s", durString)

		// Print log names.
		// Do not print log URLs because they are very long and
		// bb has `log` subcommand.
		if len(s.Logs) > 0 {
			p.f("Logs: ")
			for i, l := range s.Logs {
				if i > 0 {
					p.f(", ")
				}
				p.f("%q", l.Name)
			}
		}

		p.f("%s\n", ansi.Reset)

		p.indent.Level += 2
		if s.SummaryMarkdown != "" {
			// TODO(nodir): transform lists of links to look like logs
			p.summary(s.SummaryMarkdown)
		}
		p.indent.Level -= 2
	}
}
852243
func (c *Client) GetDockerLogs(dockerID string) (string, error) {
	var logs string
	err := c.rpcClient.Call("Agent.GetDockerLogs", dockerID, &logs, 0)
	return logs, err
}
1203438
func (containers Containers) Logs(follow bool, timestamps bool, tail string, colorize bool, since string) {
	var (
		sources         = make([]multiplexio.Source, 0, 2*len(containers))
		maxPrefixLength = strconv.Itoa(containers.maxNameLength())
	)
	appendSources := func(reader io.Reader, color *ansi.Color, name string, separator string) {
		if reader != nil {
			prefix := fmt.Sprintf("%"+maxPrefixLength+"s "+separator+" ", name)
			sources = append(sources, multiplexio.Source{
				Reader: reader,
				Write:  write(prefix, color, timestamps),
			})
		}
	}
	counter := 0
	for _, container := range containers {
		var (
			logs        = container.Logs(follow, since, tail)
			stdoutColor *ansi.Color
			stderrColor *ansi.Color
		)
		for _, log := range logs {
			if colorize {
				// red has a negative/error connotation, so skip it
				ansiAttribute := ansi.Attribute(int(ansi.FgGreen) + counter%int(ansi.FgWhite-ansi.FgGreen))
				stdoutColor = ansi.New(ansiAttribute)
				// To synchronize their output, we need to multiplex stdout & stderr
				// onto the same stream. Unfortunately, that means that the user won't
				// be able to pipe them separately, so we use bold as a distinguishing
				// characteristic.
				stderrColor = ansi.New(ansiAttribute).Add(ansi.Bold)
			}
			appendSources(log.Stdout, stdoutColor, log.Name, "|")
			appendSources(log.Stderr, stderrColor, log.Name, "*")
			counter += 1
		}
	}
	if len(sources) > 0 {
		aggregatedReader := multiplexio.NewReader(multiplexio.Options{}, sources...)
		io.Copy(os.Stdout, aggregatedReader)
	}
}