Skip to content

Commit

Permalink
gofmt, govet
Browse files Browse the repository at this point in the history
  • Loading branch information
Mateusz 'Serafin' Gajewski committed Aug 25, 2017
1 parent 2a402c5 commit da9506f
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 57 deletions.
42 changes: 42 additions & 0 deletions flags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package main

import (
"flag"
"fmt"
"strings"
)

type argumentList struct {
name string
values []string
}

func (al *argumentList) String() string {
return fmt.Sprintf("%s = %s", al.name, strings.Join(al.values, ", "))
}

func (al *argumentList) Set(value string) error {
al.values = append(al.values, value)
return nil
}

var filterInclude = &argumentList{name: "include", values: []string{}}
var filterExclude = &argumentList{name: "exclude", values: []string{}}

var (
flagListen = flag.String("l", "localhost:9223", "listen address")
flagRemote = flag.String("r", "localhost:9222", "remote address")
flagEllipsis = flag.Bool("s", false, "shorten requests and responses")
flagOnce = flag.Bool("once", false, "debug single session")
flagShowRequests = flag.Bool("i", false, "include request frames as they are sent")
flagDistributeLogs = flag.Bool("d", false, "write logs file per targetId")
flagQuiet = flag.Bool("q", false, "do not show logs on stdout")
flagMicroseconds = flag.Bool("m", false, "display time in microseconds")
flagDelta = flag.Bool("delta", false, "show delta time between log entries")
flagDirLogs = flag.String("log-dir", "logs", "logs directory")
)

func init() {
flag.Var(filterInclude, "include", "display only requests/responses/events matching pattern")
flag.Var(filterExclude, "exclude", "exclude requests/responses/events matching pattern")
}
31 changes: 17 additions & 14 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ package main

import (
"fmt"
"github.com/Sirupsen/logrus"
"github.com/fatih/color"
"io"
"io/ioutil"
"math"
"os"
"path/filepath"
"time"

"github.com/Sirupsen/logrus"
"github.com/fatih/color"
)

const (
Expand All @@ -28,11 +29,11 @@ const (
const (
fieldLevel = "level"
fieldType = "type"
fieldTargetId = "targetId"
fieldSessionId = "sessionId"
fieldTargetID = "targetID"
fieldSessionID = "sessionID"
fieldRequest = "request"
fieldMethod = "method"
fieldInspectorId = "inspectorId"
fieldInspectorID = "inspectorId"
)

const (
Expand All @@ -41,6 +42,7 @@ const (
eventFormat = "%-17s %s % 48s(%s)\n"
protocolFormat = "%-17s %s\n"
timeFormat = "15:04:05.00000000"
deltaFormat = "Δ%8.2fms"
)

var (
Expand All @@ -53,6 +55,7 @@ var (
targetColor = color.New(color.FgHiWhite).SprintfFunc()
methodColor = color.New(color.FgHiYellow).SprintfFunc()
errorColor = color.New(color.BgRed, color.FgWhite).SprintfFunc()
protocolTargetID = center("protocol message", 36)
)

type FramesFormatter struct {
Expand All @@ -73,18 +76,18 @@ func (f *FramesFormatter) Format(e *logrus.Entry) ([]byte, error) {
var delta string

if f.lastTime == 0 {
delta = fmt.Sprintf("Δ%8.2fms", 0.00)
delta = fmt.Sprintf(deltaFormat, 0.00)
} else {
delta = fmt.Sprintf("Δ%8.2fms", math.Abs(float64(e.Time.UnixNano()-f.lastTime)/float64(time.Millisecond)))
delta = fmt.Sprintf(deltaFormat, math.Abs(float64(e.Time.UnixNano()-f.lastTime)/float64(time.Millisecond)))
}

f.lastTime = e.Time.UnixNano()

timestamp = fmt.Sprintf("%s %s", timestamp, delta)
}

var protocolType int = -1
var protocolMethod string = ""
var protocolType = -1
var protocolMethod = ""

protocolLevel := e.Data[fieldLevel].(int)

Expand All @@ -106,20 +109,20 @@ func (f *FramesFormatter) Format(e *logrus.Entry) ([]byte, error) {
}

case levelProtocol, levelTarget:
targetId := e.Data[fieldTargetId].(string)
targetID := e.Data[fieldTargetID].(string)

switch protocolType {
case typeEvent:
return []byte(fmt.Sprintf(eventFormat, timestamp, targetColor(targetId), methodColor(protocolMethod), eventsColor(message))), nil
return []byte(fmt.Sprintf(eventFormat, timestamp, targetColor(targetID), methodColor(protocolMethod), eventsColor(message))), nil

case typeRequest:
return []byte(fmt.Sprintf(requestFormat, timestamp, targetColor(targetId), methodColor(protocolMethod), requestColor(message))), nil
return []byte(fmt.Sprintf(requestFormat, timestamp, targetColor(targetID), methodColor(protocolMethod), requestColor(message))), nil

case typeRequestResponse:
return []byte(fmt.Sprintf(requestReplyFormat, timestamp, targetColor(targetId), methodColor(protocolMethod), requestReplyColor(e.Data[fieldRequest].(string)), responseColor(message))), nil
return []byte(fmt.Sprintf(requestReplyFormat, timestamp, targetColor(targetID), methodColor(protocolMethod), requestReplyColor(e.Data[fieldRequest].(string)), responseColor(message))), nil

case typeRequestResponseError:
return []byte(fmt.Sprintf(requestReplyFormat, timestamp, targetColor(targetId), methodColor(protocolMethod), requestReplyColor(e.Data[fieldRequest].(string)), errorColor(message))), nil
return []byte(fmt.Sprintf(requestReplyFormat, timestamp, targetColor(targetID), methodColor(protocolMethod), requestReplyColor(e.Data[fieldRequest].(string)), errorColor(message))), nil
}
}

Expand Down
47 changes: 16 additions & 31 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,6 @@ import (
"github.com/Sirupsen/logrus"
)

var (
flagListen = flag.String("l", "localhost:9223", "listen address")
flagRemote = flag.String("r", "localhost:9222", "remote address")
flagEllipsis = flag.Bool("s", false, "shorten requests and responses")
flagOnce = flag.Bool("once", false, "debug single session")
flagShowRequests = flag.Bool("i", false, "include request frames as they are sent")
flagDistributeLogs = flag.Bool("d", false, "write logs file per targetId")
flagQuiet = flag.Bool("q", false, "do not show logs on stdout")
flagMicroseconds = flag.Bool("m", false, "display time in microseconds")
flagDelta = flag.Bool("delta", false, "show delta time between log entries")
flagDirLogs = flag.String("log-dir", "logs", "logs directory")
)

var protocolTargetID = center("protocol message", 36)

func main() {
flag.Parse()

Expand Down Expand Up @@ -69,12 +54,12 @@ func main() {

protocolLogger = logger.WithFields(logrus.Fields{
fieldLevel: levelConnection,
fieldInspectorId: id,
fieldInspectorID: id,
})

} else {
protocolLogger = logger.WithFields(logrus.Fields{
fieldInspectorId: id,
fieldInspectorID: id,
})
}

Expand Down Expand Up @@ -162,28 +147,28 @@ func dumpStream(logger *logrus.Entry, stream chan *protocolMessage) {
var targetLogger *logrus.Entry

if *flagDistributeLogs {
logger, err := createLogger(fmt.Sprintf("target-%s", msg.TargetId()))
logger, err := createLogger(fmt.Sprintf("target-%s", msg.TargetID()))
if err != nil {
panic(fmt.Sprintf("could not create logger: %v", err))
}

targetLogger = logger.WithFields(logrus.Fields{
fieldLevel: levelTarget,
fieldTargetId: msg.TargetId(),
fieldTargetID: msg.TargetID(),
})

} else {
targetLogger = logger.WithFields(logrus.Fields{
fieldLevel: levelTarget,
fieldTargetId: msg.TargetId(),
fieldTargetID: msg.TargetID(),
})
}

if msg.IsRequest() {
requests[msg.Id] = nil
requests[msg.ID] = nil

if protocolMessage, err := decodeMessage([]byte(asString(msg.Params["message"]))); err == nil {
targetRequests[protocolMessage.Id] = protocolMessage
targetRequests[protocolMessage.ID] = protocolMessage

if *flagShowRequests {
targetLogger.WithFields(logrus.Fields{
Expand All @@ -195,7 +180,7 @@ func dumpStream(logger *logrus.Entry, stream chan *protocolMessage) {
} else {
logger.WithFields(logrus.Fields{
fieldLevel: levelConnection,
}).Error("Could not deserialize message: %+v", err)
}).Errorf("Could not deserialize message: %+v", err)
}
}

Expand All @@ -222,13 +207,13 @@ func dumpStream(logger *logrus.Entry, stream chan *protocolMessage) {
logType = typeRequestResponse
}

if request, ok := targetRequests[protocolMessage.Id]; ok && request != nil {
delete(targetRequests, protocolMessage.Id)
if request, ok := targetRequests[protocolMessage.ID]; ok && request != nil {
delete(targetRequests, protocolMessage.ID)
logRequest = serialize(request.Params)
logMethod = request.Method

} else {
logRequest = errorColor("could not find request with id: %d", protocolMessage.Id)
logRequest = errorColor("could not find request with id: %d", protocolMessage.ID)
}

targetLogger.WithFields(logrus.Fields{
Expand All @@ -240,18 +225,18 @@ func dumpStream(logger *logrus.Entry, stream chan *protocolMessage) {
} else {
logger.WithFields(logrus.Fields{
fieldLevel: levelConnection,
}).Error("Could not deserialize message: %+v", err)
}).Errorf("Could not deserialize message: %+v", err)
}
}

} else {
protocolLogger := logger.WithFields(logrus.Fields{
fieldLevel: levelProtocol,
fieldTargetId: protocolTargetID,
fieldTargetID: protocolTargetID,
})

if msg.IsRequest() {
requests[msg.Id] = msg
requests[msg.ID] = msg

if *flagShowRequests {
protocolLogger.WithFields(logrus.Fields{
Expand All @@ -276,11 +261,11 @@ func dumpStream(logger *logrus.Entry, stream chan *protocolMessage) {
logType = typeRequestResponse
}

if request, ok := requests[msg.Id]; ok && request != nil {
if request, ok := requests[msg.ID]; ok && request != nil {
logRequest = serialize(request.Params)
logMethod = request.Method

delete(requests, msg.Id)
delete(requests, msg.ID)

protocolLogger.WithFields(logrus.Fields{
fieldType: logType,
Expand Down
14 changes: 7 additions & 7 deletions protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package main
import "fmt"

type protocolMessage struct {
Id uint64 `json:"id"`
ID uint64 `json:"id"`
Result map[string]interface{} `json:"result"`
Error struct {
Code int64 `json:"code"`
Expand All @@ -15,8 +15,8 @@ type protocolMessage struct {
}

type targetedProtocolMessage struct {
TargetId string `json:"targetId"`
SessionId string `json:"sessionId"`
TargetID string `json:"targetId"`
SessionID string `json:"sessionId"`
Message string `json:"message"`
}

Expand All @@ -27,7 +27,7 @@ func (t *targetedProtocolMessage) ProtocolMessage() (*protocolMessage, error) {
func (p *protocolMessage) String() string {
return fmt.Sprintf(
"protocolMessage{id=%d, method=%s, result=%+v, error=%+v, params=%+v}",
p.Id,
p.ID,
p.Method,
p.Result,
p.Error,
Expand All @@ -40,11 +40,11 @@ func (p *protocolMessage) IsError() bool {
}

func (p *protocolMessage) IsResponse() bool {
return p.Method == "" && p.Id > 0
return p.Method == "" && p.ID > 0
}

func (p *protocolMessage) IsRequest() bool {
return p.Method != "" && p.Id > 0
return p.Method != "" && p.ID > 0
}

func (p *protocolMessage) IsEvent() bool {
Expand All @@ -55,7 +55,7 @@ func (p *protocolMessage) InTarget() bool {
return p.Method == "Target.sendMessageToTarget" || p.Method == "Target.receivedMessageFromTarget"
}

func (p *protocolMessage) TargetId() string {
func (p *protocolMessage) TargetID() string {
if p.InTarget() {
if val, ok := p.Params["sessionId"]; ok {
return val.(string)
Expand Down
10 changes: 5 additions & 5 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@ func center(message string, length int) string {

if padding < 0 {
return message
} else {
return strings.Repeat(" ", padding) + message + strings.Repeat(" ", length-len(message)-padding)
}

return strings.Repeat(" ", padding) + message + strings.Repeat(" ", length-len(message)-padding)
}

func asString(value interface{}) string {
Expand All @@ -31,7 +30,8 @@ func asString(value interface{}) string {

func serialize(value interface{}) string {

if buff, err := json.Marshal(value); err == nil {
buff, err := json.Marshal(value)
if err == nil {
if *flagEllipsis && len(buff) > ellipsisLength {
return string(buff[:ellipsisLength]) + "..."
}
Expand All @@ -43,9 +43,9 @@ func serialize(value interface{}) string {
}

return serialized
} else {
return err.Error()
}

return err.Error()
}

func decodeMessage(bytes []byte) (*protocolMessage, error) {
Expand Down

0 comments on commit da9506f

Please sign in to comment.