11 "golang.org/x/tools/internal/jsonrpc2"
14 type loggingStream struct {
15 stream jsonrpc2.Stream
20 // LoggingStream returns a stream that does LSP protocol logging too
21 func LoggingStream(str jsonrpc2.Stream, w io.Writer) jsonrpc2.Stream {
22 return &loggingStream{stream: str, log: w}
25 func (s *loggingStream) Read(ctx context.Context) (jsonrpc2.Message, int64, error) {
26 msg, count, err := s.stream.Read(ctx)
28 s.logCommon(msg, true)
30 return msg, count, err
33 func (s *loggingStream) Write(ctx context.Context, msg jsonrpc2.Message) (int64, error) {
34 s.logCommon(msg, false)
35 count, err := s.stream.Write(ctx, msg)
39 func (s *loggingStream) Close() error {
40 return s.stream.Close()
50 clientCalls map[string]req
51 serverCalls map[string]req
60 // these 4 methods are each used exactly once, but it seemed
61 // better to have the encapsulation rather than ad hoc mutex
63 func (m *mapped) client(id string) req {
66 v := m.clientCalls[id]
67 delete(m.clientCalls, id)
71 func (m *mapped) server(id string) req {
74 v := m.serverCalls[id]
75 delete(m.serverCalls, id)
79 func (m *mapped) setClient(id string, r req) {
85 func (m *mapped) setServer(id string, r req) {
91 const eor = "\r\n\r\n\r\n"
93 func (s *loggingStream) logCommon(msg jsonrpc2.Message, isRead bool) {
95 defer s.logMu.Unlock()
96 direction, pastTense := "Received", "Received"
97 get, set := maps.client, maps.setServer
99 direction, pastTense = "Sending", "Sent"
100 get, set = maps.server, maps.setClient
102 if msg == nil || s.log == nil {
106 tmfmt := tm.Format("15:04:05.000 PM")
108 buf := strings.Builder{}
109 fmt.Fprintf(&buf, "[Trace - %s] ", tmfmt) // common beginning
110 switch msg := msg.(type) {
112 id := fmt.Sprint(msg.ID())
113 fmt.Fprintf(&buf, "%s request '%s - (%s)'.\n", direction, msg.Method(), id)
114 fmt.Fprintf(&buf, "Params: %s%s", msg.Params(), eor)
115 set(id, req{method: msg.Method(), start: tm})
116 case *jsonrpc2.Notification:
117 fmt.Fprintf(&buf, "%s notification '%s'.\n", direction, msg.Method())
118 fmt.Fprintf(&buf, "Params: %s%s", msg.Params(), eor)
119 case *jsonrpc2.Response:
120 id := fmt.Sprint(msg.ID())
121 if err := msg.Err(); err != nil {
122 fmt.Fprintf(s.log, "[Error - %s] %s #%s %s%s", pastTense, tmfmt, id, err, eor)
126 elapsed := tm.Sub(cc.start)
127 fmt.Fprintf(&buf, "%s response '%s - (%s)' in %dms.\n",
128 direction, cc.method, id, elapsed/time.Millisecond)
129 fmt.Fprintf(&buf, "Result: %s%s", msg.Result(), eor)
131 s.log.Write([]byte(buf.String()))