1// Copyright 2018 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5package jsonrpc2 6 7import ( 8 "encoding/json" 9 "log" 10 "time" 11) 12 13// Logger is an option you can pass to NewConn which is invoked for 14// all messages flowing through a Conn. 15// direction indicates if the message being recieved or sent 16// id is the message id, if not set it was a notification 17// elapsed is the time between a call being seen and the response, and is 18// negative for anything that is not a response. 19// method is the method name specified in the message 20// payload is the parameters for a call or notification, and the result for a 21// response 22type Logger = func(direction Direction, id *ID, elapsed time.Duration, method string, payload *json.RawMessage, err *Error) 23 24// Direction is used to indicate to a logger whether the logged message was being 25// sent or received. 26type Direction bool 27 28const ( 29 // Send indicates the message is outgoing. 30 Send = Direction(true) 31 // Receive indicates the message is incoming. 32 Receive = Direction(false) 33) 34 35func (d Direction) String() string { 36 switch d { 37 case Send: 38 return "send" 39 case Receive: 40 return "receive" 41 default: 42 panic("unreachable") 43 } 44} 45 46// Log is an implementation of Logger that outputs using log.Print 47// It is not used by default, but is provided for easy logging in users code. 48func Log(direction Direction, id *ID, elapsed time.Duration, method string, payload *json.RawMessage, err *Error) { 49 switch { 50 case err != nil: 51 log.Printf("%v failure [%v] %s %v", direction, id, method, err) 52 case id == nil: 53 log.Printf("%v notification %s %s", direction, method, *payload) 54 case elapsed >= 0: 55 log.Printf("%v response in %v [%v] %s %s", direction, elapsed, id, method, *payload) 56 default: 57 log.Printf("%v call [%v] %s %s", direction, id, method, *payload) 58 } 59} 60