github.com/getgauge/gauge@v1.6.9/api/lang/logger.go (about) 1 /*---------------------------------------------------------------- 2 * Copyright (c) ThoughtWorks, Inc. 3 * Licensed under the Apache License, Version 2.0 4 * See LICENSE in the project root for license information. 5 *----------------------------------------------------------------*/ 6 7 package lang 8 9 import ( 10 "context" 11 "fmt" 12 "os" 13 14 "github.com/getgauge/gauge/logger" 15 "github.com/sourcegraph/go-langserver/pkg/lsp" 16 "github.com/sourcegraph/jsonrpc2" 17 ) 18 19 type lspWriter struct { 20 } 21 22 func (w lspWriter) Write(p []byte) (n int, err error) { 23 logger.Debug(false, string(p)) 24 return os.Stderr.Write(p) 25 } 26 27 type stdRWC struct{} 28 29 func (stdRWC) Read(p []byte) (int, error) { 30 return os.Stdin.Read(p) 31 } 32 33 func (stdRWC) Write(p []byte) (int, error) { 34 return os.Stdout.Write(p) 35 } 36 37 func (stdRWC) Close() error { 38 if err := os.Stdin.Close(); err != nil { 39 return err 40 } 41 return os.Stdout.Close() 42 } 43 44 type lspLogger struct { 45 conn *jsonrpc2.Conn 46 ctx context.Context 47 } 48 49 func (c *lspLogger) Log(level lsp.MessageType, msg string) { 50 err := c.conn.Notify(c.ctx, "window/logMessage", lsp.LogMessageParams{Type: level, Message: msg}) 51 if err != nil { 52 logger.Errorf(false, "Unable to log error '%s' to LSP: %s", msg, err.Error()) 53 } 54 } 55 56 var lspLog *lspLogger 57 58 func initialize(ctx context.Context, conn *jsonrpc2.Conn) { 59 lspLog = &lspLogger{conn: conn, ctx: ctx} 60 } 61 62 func logDebug(req *jsonrpc2.Request, msg string, args ...interface{}) { 63 m := fmt.Sprintf(getLogFormatFor(req, msg), args...) 64 logger.Debug(false, m) 65 logToLsp(lsp.Log, m) 66 } 67 68 func logInfo(req *jsonrpc2.Request, msg string, args ...interface{}) { 69 m := fmt.Sprintf(getLogFormatFor(req, msg), args...) 70 logger.Info(false, m) 71 logToLsp(lsp.Info, m) 72 } 73 74 func logWarning(req *jsonrpc2.Request, msg string, args ...interface{}) { 75 m := fmt.Sprintf(getLogFormatFor(req, msg), args...) 76 logger.Warning(false, m) 77 logToLsp(lsp.MTWarning, m) 78 } 79 80 func logError(req *jsonrpc2.Request, msg string, args ...interface{}) { 81 m := fmt.Sprintf(getLogFormatFor(req, msg), args...) 82 logger.Error(false, m) 83 logToLsp(lsp.MTError, m) 84 } 85 86 func logFatal(req *jsonrpc2.Request, msg string, args ...interface{}) { 87 logToLsp(lsp.MTError, "An error occurred. Refer lsp.log for more details.") 88 logger.Fatalf(true, getLogFormatFor(req, msg), args...) 89 } 90 91 func logToLsp(level lsp.MessageType, m string) { 92 if lspLog != nil { 93 lspLog.Log(level, m) 94 } 95 } 96 func getLogFormatFor(req *jsonrpc2.Request, msg string) string { 97 if req == nil { 98 return msg 99 } 100 formattedMsg := fmt.Sprintf("#%s: %s: ", req.ID.String(), req.Method) + msg 101 if req.Notif { 102 return "notif " + formattedMsg 103 } 104 return "request " + formattedMsg 105 }