github.com/beornf/libcompose@v0.4.1-0.20210215180846-a59802c0f07c/cli/app/events.go (about)

     1  package app
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"os"
     7  	"strings"
     8  
     9  	"golang.org/x/net/context"
    10  
    11  	"github.com/docker/libcompose/project"
    12  	"github.com/docker/libcompose/project/events"
    13  	"github.com/sirupsen/logrus"
    14  	"github.com/urfave/cli"
    15  )
    16  
    17  // ProjectEvents listen for real-time events of containers.
    18  func ProjectEvents(p project.APIProject, c *cli.Context) error {
    19  	evts, err := p.Events(context.Background(), c.Args()...)
    20  	if err != nil {
    21  		return err
    22  	}
    23  	var printfn func(events.ContainerEvent)
    24  
    25  	if c.Bool("json") {
    26  		printfn = printJSON
    27  	} else {
    28  		printfn = printStd
    29  	}
    30  	for event := range evts {
    31  		printfn(event)
    32  	}
    33  	return nil
    34  }
    35  
    36  func printStd(event events.ContainerEvent) {
    37  	output := os.Stdout
    38  	fmt.Fprintf(output, "%s ", event.Time.Format("2006-01-02 15:04:05.999999999"))
    39  	fmt.Fprintf(output, "%s %s %s", event.Type, event.Event, event.ID)
    40  	attrs := []string{}
    41  	for attr, value := range event.Attributes {
    42  		attrs = append(attrs, fmt.Sprintf("%s=%s", attr, value))
    43  	}
    44  
    45  	fmt.Fprintf(output, " (%s)", strings.Join(attrs, ", "))
    46  	fmt.Fprint(output, "\n")
    47  }
    48  
    49  func printJSON(event events.ContainerEvent) {
    50  	json, err := json.Marshal(event)
    51  	if err != nil {
    52  		logrus.Warn(err)
    53  	}
    54  	output := os.Stdout
    55  	fmt.Fprintf(output, "%s", json)
    56  }