Skip to content

Commit

Permalink
Extract message printing code and output config
Browse files Browse the repository at this point in the history
  • Loading branch information
TylerBrock committed May 28, 2018
1 parent b57079e commit 05a94dc
Show file tree
Hide file tree
Showing 8 changed files with 98 additions and 60 deletions.
41 changes: 24 additions & 17 deletions blade/blade.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"sort"
"time"

"github.com/TylerBrock/colorjson"
"github.com/TylerBrock/saw/config"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/endpoints"
Expand All @@ -17,17 +18,19 @@ import (

type Blade struct {
config *config.Configuration
output *config.OutputConfiguration
cwl *cloudwatchlogs.CloudWatchLogs
}

func NewBlade(config *config.Configuration) *Blade {
func NewBlade(config *config.Configuration, outputConfig *config.OutputConfiguration) *Blade {
blade := Blade{}
region := endpoints.UsEast1RegionID
awsConfig := aws.Config{Region: &region}
sess := session.Must(session.NewSession(&awsConfig))

blade.cwl = cloudwatchlogs.New(sess)
blade.config = config
blade.output = outputConfig

return &blade
}
Expand Down Expand Up @@ -65,7 +68,7 @@ func (b *Blade) GetLogStreams() []*cloudwatchlogs.LogStream {

func (b *Blade) StreamEvents() {
var lastSeenTime *int64
formatter := b.config.Formatter()
formatter := b.output.Formatter()
input := b.config.FilterLogEventsInput()

updateLastSeenTime := func(ts *int64) {
Expand All @@ -75,22 +78,8 @@ func (b *Blade) StreamEvents() {
}

handlePage := func(page *cloudwatchlogs.FilterLogEventsOutput, lastPage bool) bool {
red := color.New(color.FgRed).SprintFunc()
white := color.New(color.FgWhite).SprintFunc()

for _, event := range page.Events {
str := aws.StringValue(event.Message)
bytes := []byte(str)
date := aws.MillisecondsTimeValue(event.Timestamp)
dateStr := date.Format(time.RFC3339)
streamStr := aws.StringValue(event.LogStreamName)
jl := map[string]interface{}{}
if err := json.Unmarshal(bytes, &jl); err != nil {
fmt.Printf("[%s] (%s) %s\n", red(dateStr), white(streamStr), str)
} else {
output, _ := formatter.Marshal(jl)
fmt.Printf("[%s] (%s) %s\n", red(dateStr), white(streamStr), output)
}
printEvent(formatter, event)
updateLastSeenTime(event.Timestamp)
}
return !lastPage
Expand All @@ -109,6 +98,24 @@ func (b *Blade) StreamEvents() {
}
}

func printEvent(formatter *colorjson.Formatter, event *cloudwatchlogs.FilteredLogEvent) {
red := color.New(color.FgRed).SprintFunc()
white := color.New(color.FgWhite).SprintFunc()

str := aws.StringValue(event.Message)
bytes := []byte(str)
date := aws.MillisecondsTimeValue(event.Timestamp)
dateStr := date.Format(time.RFC3339)
streamStr := aws.StringValue(event.LogStreamName)
jl := map[string]interface{}{}
if err := json.Unmarshal(bytes, &jl); err != nil {
fmt.Printf("[%s] (%s) %s\n", red(dateStr), white(streamStr), str)
} else {
output, _ := formatter.Marshal(jl)
fmt.Printf("[%s] (%s) %s\n", red(dateStr), white(streamStr), output)
}
}

func topStreamNames(streams []*cloudwatchlogs.LogStream) []*string {
// FilerLogEvents can only take 100 streams so lets sort by LastEventTimestamp
// (descending) and take only the names of the most recent 100.
Expand Down
16 changes: 15 additions & 1 deletion cmd/get.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,31 @@
package cmd

import (
"errors"

"github.com/TylerBrock/saw/config"
"github.com/spf13/cobra"
)

var getConfig config.Configuration

var Get = &cobra.Command{
var GetCommand = &cobra.Command{
Use: "get",
Short: "Get log events",
Long: "",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("listing streams requires log group argument")
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
//b := blade.NewBlade(&getConfig)
},
}

func init() {
GetCommand.Flags().StringVar(&groupsConfig.Prefix, "prefix", "", "log group prefix filter")
GetCommand.Flags().StringVar(&groupsConfig.Start, "start", "", "start getting the logs from this point")
GetCommand.Flags().StringVar(&groupsConfig.End, "end", "now", "stop getting the logs at this point")
}
2 changes: 1 addition & 1 deletion cmd/groups.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ var GroupsCommand = &cobra.Command{
Short: "List log groups",
Long: "",
Run: func(cmd *cobra.Command, args []string) {
b := blade.NewBlade(&groupsConfig)
b := blade.NewBlade(&groupsConfig, nil)
logGroups := b.GetLogGroups()
for _, group := range logGroups {
fmt.Println(*group.LogGroupName)
Expand Down
4 changes: 3 additions & 1 deletion cmd/saw.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cmd

import "github.com/spf13/cobra"
import (
"github.com/spf13/cobra"
)

var SawCommand = &cobra.Command{
Use: "saw",
Expand Down
4 changes: 3 additions & 1 deletion cmd/streams.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ var StreamsCommand = &cobra.Command{
},
Run: func(cmd *cobra.Command, args []string) {
streamsConfig.Group = args[0]
b := blade.NewBlade(&streamsConfig)
b := blade.NewBlade(&streamsConfig, nil)

logStreams := b.GetLogStreams()
for _, stream := range logStreams {
Expand All @@ -34,4 +34,6 @@ var StreamsCommand = &cobra.Command{

func init() {
StreamsCommand.Flags().StringVar(&streamsConfig.Prefix, "prefix", "", "stream prefix filter")
StreamsCommand.Flags().StringVar(&streamsConfig.OrderBy, "orderBy", "LogStreamName", "order streams by LogStreamName or LastEventTime")
StreamsCommand.Flags().BoolVar(&streamsConfig.Descending, "descending", false, "order streams descending")
}
9 changes: 5 additions & 4 deletions cmd/watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
)

var watchConfig config.Configuration
var outputConfig config.OutputConfiguration

var WatchCommand = &cobra.Command{
Use: "watch <log group>",
Expand All @@ -22,15 +23,15 @@ var WatchCommand = &cobra.Command{
},
Run: func(cmd *cobra.Command, args []string) {
watchConfig.Group = args[0]
b := blade.NewBlade(&watchConfig)
b := blade.NewBlade(&watchConfig, &outputConfig)
b.StreamEvents()
},
}

func init() {
WatchCommand.Flags().StringVar(&watchConfig.Prefix, "prefix", "", "log group prefix filter")
WatchCommand.Flags().StringVar(&watchConfig.Filter, "filter", "", "event filter pattern")
WatchCommand.Flags().BoolVar(&watchConfig.Expand, "expand", false, "indent JSON log messages")
WatchCommand.Flags().BoolVar(&watchConfig.Invert, "invert", false, "invert colors for light terminal themes")
WatchCommand.Flags().BoolVar(&watchConfig.RawString, "rawString", false, "print JSON strings without escaping")
WatchCommand.Flags().BoolVar(&outputConfig.Expand, "expand", false, "indent JSON log messages")
WatchCommand.Flags().BoolVar(&outputConfig.Invert, "invert", false, "invert colors for light terminal themes")
WatchCommand.Flags().BoolVar(&outputConfig.RawString, "rawString", false, "print JSON strings without escaping")
}
45 changes: 10 additions & 35 deletions config/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,21 @@ import (
"errors"
"time"

"github.com/TylerBrock/colorjson"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"github.com/fatih/color"
)

const maxLimit = 50

type Configuration struct {
Group string
Prefix string
Start string
End string
Filter string
Region string
Expand bool
Raw bool
RawString bool
Invert bool
NoColor bool
Group string
Prefix string
Start string
End string
Filter string
Region string
Descending bool
OrderBy string
}

func getTime(timeStr string) (time.Time, error) {
Expand Down Expand Up @@ -51,6 +46,8 @@ func (c *Configuration) DescribeLogGroupsInput() *cloudwatchlogs.DescribeLogGrou
func (c *Configuration) DescribeLogStreamsInput() *cloudwatchlogs.DescribeLogStreamsInput {
input := cloudwatchlogs.DescribeLogStreamsInput{}
input.SetLogGroupName(c.Group)
input.SetDescending(c.Descending)
input.SetOrderBy(c.OrderBy)
if c.Prefix != "" {
input.SetLogStreamNamePrefix(c.Prefix)
}
Expand Down Expand Up @@ -84,25 +81,3 @@ func (c *Configuration) FilterLogEventsInput() *cloudwatchlogs.FilterLogEventsIn

return &input
}

func (c *Configuration) Formatter() *colorjson.Formatter {
var formatter *colorjson.Formatter = colorjson.NewFormatter()

if c.Expand {
formatter.Indent = 4
}

if c.RawString {
formatter.RawStrings = true
}

if c.Invert {
formatter.KeyColor = color.New(color.FgBlack)
}

if c.NoColor {
color.NoColor = true
}

return formatter
}
37 changes: 37 additions & 0 deletions config/output.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package config

import (
"github.com/TylerBrock/colorjson"
"github.com/fatih/color"
)

type OutputConfiguration struct {
Expand bool
Raw bool
RawString bool
ShowStreamName bool
Invert bool
NoColor bool
}

func (c *OutputConfiguration) Formatter() *colorjson.Formatter {
var formatter *colorjson.Formatter = colorjson.NewFormatter()

if c.Expand {
formatter.Indent = 4
}

if c.RawString {
formatter.RawStrings = true
}

if c.Invert {
formatter.KeyColor = color.New(color.FgBlack)
}

if c.NoColor {
color.NoColor = true
}

return formatter
}

0 comments on commit 05a94dc

Please sign in to comment.