github.com/vmware/govmomi@v0.37.2/toolbox/trace_channel.go (about) 1 /* 2 Copyright (c) 2017 VMware, Inc. All Rights Reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package toolbox 18 19 import ( 20 "encoding/hex" 21 "flag" 22 "fmt" 23 "io" 24 "os" 25 ) 26 27 var ( 28 Trace = false 29 30 traceLog io.Writer = os.Stderr 31 ) 32 33 func init() { 34 flag.BoolVar(&Trace, "toolbox.trace", Trace, "Enable toolbox trace") 35 } 36 37 type TraceChannel struct { 38 Channel 39 log io.Writer 40 } 41 42 func NewTraceChannel(c Channel) Channel { 43 if !Trace { 44 return c 45 } 46 47 return &TraceChannel{ 48 Channel: c, 49 log: traceLog, 50 } 51 } 52 53 func (d *TraceChannel) Start() error { 54 err := d.Channel.Start() 55 56 return err 57 } 58 59 func (d *TraceChannel) Stop() error { 60 err := d.Channel.Stop() 61 62 return err 63 } 64 65 func (d *TraceChannel) Send(buf []byte) error { 66 if len(buf) > 0 { 67 fmt.Fprintf(d.log, "SEND %d...\n%s\n", len(buf), hex.Dump(buf)) 68 } 69 70 err := d.Channel.Send(buf) 71 72 return err 73 } 74 75 func (d *TraceChannel) Receive() ([]byte, error) { 76 buf, err := d.Channel.Receive() 77 78 if err == nil && len(buf) > 0 { 79 fmt.Fprintf(d.log, "RECV %d...\n%s\n", len(buf), hex.Dump(buf)) 80 } 81 82 return buf, err 83 }