Best Gauge code snippet using formatter.Step
logger.go
Source:logger.go
...10 StarterPosition = "Starter"11)12// å¯å¨æ¥éª¤å¸¸é13const (14 StepInit = "Init"15 StepSetup = "Setup"16 StepStart = "Start"17 StepCheck = "Check"18 StepStop = "Hook"19)20// æ¥å¿ç级å½å常é21const (22 DebugLevel = "Debug"23 InfoLevel = "Info"24 OKLevel = "OK"25 WarningLevel = "Warning"26 ErrorLevel = "Error"27 FailLevel = "Fail"28)29const (30 whitef = "\033[37m"31 yellowf = "\033[33m"32 bluef = "\033[34m"33 greenf = "\033[32m"34 redf = "\033[31m"35 magentaf = "\033[35m"36 white = "\033[30;47m"37 green = "\033[97;42m"38 blue = "\033[97;44m"39 cyan = "\033[97;46m"40 yellow = "\033[90;43m"41 red = "\033[1;97;41m"42 magenta = "\033[1;97;45m"43 reset = "\033[0m"44)45// å¯å®ä¹å¤ä¸ªè¾åº46type StarterLoggerOutput struct {47 Formatter LogFormatter // æ ¼å¼è½¬åå¨48 Writers io.Writer // è¾åº49}50// æ ¼å¼è½¬åç¾åå½æ°51type LogFormatter func(params LogFormatterParams) string52// æ ¼å¼åè¾åºåæ°53type LogFormatterParams struct {54 Position string // æ¥å¿è®°å½ä½ç½®55 Name string // å¯å¨å¨å称56 Step string // å¯å¨å¨æ¥éª¤57 LogLevel string // è®°å½æ¥å¿çº§å«58 TimeStamp time.Time // è®°å½æ¶é´æ³59 Message string // è®°å½ä¿¡æ¯60}61// æ¥å¿è¾åºä½ç½®é¢è²æ 示62func (p *LogFormatterParams) LogPositionColor() string {63 switch p.Position {64 case StarterPosition:65 return white66 default:67 return magenta68 }69}70// å¯å¨å¨æ¥éª¤é¢è²æ 示71func (p *LogFormatterParams) LogStepColor() string {72 switch p.Step {73 case StepInit:74 return yellow75 case StepSetup:76 return cyan77 case StepStart:78 return blue79 case StepCheck:80 return green81 default:82 return red83 }84}85// æ¯ç§é误级å«è¾åºä¸åçé¢è²86func (p *LogFormatterParams) LogLevelColor() string {87 switch p.LogLevel {88 case DebugLevel:89 return bluef90 case InfoLevel:91 return whitef92 case OKLevel:93 return greenf94 case WarningLevel:95 return yellowf96 case ErrorLevel:97 return redf98 case FailLevel:99 return magentaf100 default:101 return white102 }103}104// é¢è²éç½®105func (p *LogFormatterParams) ResetColor() string {106 return reset107}108// å¯å¨æ¥å¿é»è®¤ç»ç«¯é¢è²è¾åºæ ¼å¼109var defaultLogFormatter = func(param LogFormatterParams) string {110 var positionColor, stepColor, logLevelColor, resetColor string111 positionColor = param.LogPositionColor()112 stepColor = param.LogStepColor()113 logLevelColor = param.LogLevelColor()114 resetColor = param.ResetColor()115 return fmt.Sprintf("%s %-12s %s %s %-6s %s | %v |%s [%s]\t>>> %s %s \n",116 positionColor, param.Name, resetColor,117 stepColor, param.Step, resetColor,118 param.TimeStamp.Format("2006/01/02 - 15:04:05"),119 logLevelColor, param.LogLevel, param.Message, resetColor,120 )121}122// å¯å¨æ¥å¿æ件è¾åºæ ¼å¼123var commonWriterFormatter = func(param LogFormatterParams) string {124 return fmt.Sprintf("| %s %s | %s | %v |[%s]\t>>> %s \n",125 param.Name,126 param.Position,127 param.Step,128 param.TimeStamp.Format("2006/01/02 - 15:04:05"),129 param.LogLevel, param.Message,130 )131}132type IStarterLogger interface {133 Debug(name, step, msg string)134 Info(name, step, msg string)135 OK(name, step, msg string)136 Warning(name, step, msg string)137 Error(name, step string, err error)138 Fail(name, step string, err error)139}140// å¯å¨å¨æ¥å¿è®°å½å¨141type StarterLogger struct {142 Outputs []*StarterLoggerOutput143 env string144}145func (l *StarterLogger) Debug(name, step, msg string) {146 if l.env == "debug" {147 for _, o := range l.Outputs {148 _, _ = fmt.Fprint(o.Writers, o.Formatter(LogFormatterParams{149 Position: StarterPosition,150 Name: name,151 LogLevel: DebugLevel,152 Step: step,153 TimeStamp: time.Now(),154 Message: msg,155 // å¯å¢å caller156 }))157 }158 }159}160func (l *StarterLogger) Info(name, step, msg string) {161 for _, o := range l.Outputs {162 _, _ = fmt.Fprint(o.Writers, o.Formatter(LogFormatterParams{163 Position: StarterPosition,164 Name: name,165 LogLevel: InfoLevel,166 Step: step,167 TimeStamp: time.Now(),168 Message: msg,169 }))170 }171}172func (l *StarterLogger) OK(name, step, msg string) {173 for _, o := range l.Outputs {174 _, _ = fmt.Fprint(o.Writers, o.Formatter(LogFormatterParams{175 Position: StarterPosition,176 Name: name,177 LogLevel: OKLevel,178 Step: step,179 TimeStamp: time.Now(),180 Message: msg,181 }))182 }183}184func (l *StarterLogger) Warning(name, step, msg string) {185 for _, o := range l.Outputs {186 _, _ = fmt.Fprint(o.Writers, o.Formatter(LogFormatterParams{187 Position: StarterPosition,188 Name: name,189 LogLevel: WarningLevel,190 Step: step,191 TimeStamp: time.Now(),192 Message: msg,193 }))194 }195}196func (l *StarterLogger) Error(name, step string, err error) {197 for _, o := range l.Outputs {198 _, _ = fmt.Fprint(o.Writers, o.Formatter(LogFormatterParams{199 Position: StarterPosition,200 Name: name,201 LogLevel: ErrorLevel,202 Step: step,203 TimeStamp: time.Now(),204 Message: err.Error(),205 }))206 }207}208func (l *StarterLogger) Fail(name, step string, err error) {209 for _, o := range l.Outputs {210 _, _ = fmt.Fprint(o.Writers, o.Formatter(LogFormatterParams{211 Position: StarterPosition,212 Name: name,213 LogLevel: FailLevel,214 Step: step,215 TimeStamp: time.Now(),216 Message: err.Error(),217 }))218 }219}220// æ åé¢è²è¾åºæ¥å¿è®°å½å¨221type CommandLineStarterLogger struct {222 StarterLogger223}224// é对ç»ç«¯è¾åºçé»è®¤å¯å¨æ¥å¿è®°å½å¨225func NewCommandLineStarterLogger(env string) *CommandLineStarterLogger {226 logger := new(CommandLineStarterLogger)227 output := new(StarterLoggerOutput)228 output.Formatter = defaultLogFormatter...
formatter.go
Source:formatter.go
...106 default:107 return "text/plain"108 }109}110func (f *formatter) argumentAttachment(st *godog.Step) *Attachment {111 if st.Argument == nil {112 return nil113 }114 if st.Argument.DocString != nil {115 att, err := NewAttachment("Doc", mediaType(st.Argument.DocString.MediaType),116 f.resultsPath, []byte(st.Argument.DocString.Content))117 if err != nil {118 log.Fatal("failed to create attachment:", err)119 }120 return att121 } else if st.Argument.DataTable != nil {122 mt := csvMime123 buf := bytes.NewBuffer(nil)124 c := csv.NewWriter(buf)125 for _, r := range st.Argument.DataTable.Rows {126 var rec []string127 for _, cell := range r.Cells {128 rec = append(rec, cell.Value)129 }130 if err := c.Write(rec); err != nil {131 log.Fatal("failed write csv row:", err)132 }133 }134 c.Flush()135 att, err := NewAttachment("Table", mt, f.resultsPath, buf.Bytes())136 if err != nil {137 log.Fatal("failed create table attachment:", err)138 }139 return att140 }141 return nil142}143func (f *formatter) step(st *godog.Step) Step {144 step := Step{145 Name: st.Text,146 Stage: "finished",147 Start: f.lastTime,148 }149 if att := f.argumentAttachment(st); att != nil {150 step.Attachments = append(step.Attachments, *att)151 }152 f.lastTime = getTimestampMs()153 step.Stop = f.lastTime154 return step155}156// Passed captures passed step.157func (f *formatter) Passed(_ *godog.Scenario, st *godog.Step, _ *godog.StepDefinition) {158 step := f.step(st)159 step.Status = Passed160 f.res.Steps = append(f.res.Steps, step)161 f.res.Status = Passed162}163// Skipped captures skipped step.164func (f *formatter) Skipped(_ *godog.Scenario, st *godog.Step, _ *godog.StepDefinition) {165 step := f.step(st)166 step.Status = Skipped167 f.res.Steps = append(f.res.Steps, step)168}169// Undefined captures undefined step.170func (f *formatter) Undefined(_ *godog.Scenario, st *godog.Step, _ *godog.StepDefinition) {171 step := f.step(st)172 step.Status = Broken173 f.res.Steps = append(f.res.Steps, step)174}175// Failed captures failed step.176func (f *formatter) Failed(_ *godog.Scenario, st *godog.Step, _ *godog.StepDefinition, err error) {177 details := &StatusDetails{178 Message: err.Error(),179 }180 step := f.step(st)181 step.Status = Failed182 step.StatusDetails = details183 f.res.Steps = append(f.res.Steps, step)184 f.res.Status = Failed185 f.res.StatusDetails = details186}187// Pending captures pending step.188func (f *formatter) Pending(*godog.Scenario, *godog.Step, *godog.StepDefinition) {189}190func (f *formatter) writeJSON(name string, v interface{}) {191 j, err := json.Marshal(v)192 if err != nil {193 log.Fatal("failed to marshal json value:", err)194 }195 if err := ioutil.WriteFile(f.resultsPath+"/"+name, j, 0o600); err != nil {196 log.Fatal("failed to write a file:", err)197 }198}199// Summary finishes report.200func (f *formatter) Summary() {201 if f.res != nil {202 f.writeResult(f.res)...
log.go
Source:log.go
...19func (formatter *PiperLogFormatter) Format(entry *logrus.Entry) (bytes []byte, err error) {20 message := ""21 stepName := entry.Data["stepName"]22 if stepName == nil {23 stepName = "(noStepName)"24 }25 errorMessageSnippet := ""26 if entry.Data[logrus.ErrorKey] != nil {27 errorMessageSnippet = fmt.Sprintf(" - %s", entry.Data[logrus.ErrorKey])28 }29 level, _ := entry.Level.MarshalText()30 levelString := string(level)31 if levelString == "warning" {32 levelString = "warn"33 }34 switch formatter.logFormat {35 case logFormatDefault:36 message = fmt.Sprintf("%-5s %-6s - %s%s\n", levelString, stepName, entry.Message, errorMessageSnippet)37 case logFormatWithTimestamp:38 message = fmt.Sprintf("%s %-5s %-6s %s%s\n", entry.Time.Format("15:04:05"), levelString, stepName, entry.Message, errorMessageSnippet)39 case logFormatPlain:40 message = fmt.Sprintf("%s%s\n", entry.Message, errorMessageSnippet)41 default:42 formattedMessage, err := formatter.TextFormatter.Format(entry)43 if err != nil {44 return nil, err45 }46 message = string(formattedMessage)47 }48 for _, secret := range secrets {49 message = strings.Replace(message, secret, "****", -1)50 }51 return []byte(message), nil52}53// LibraryRepository that is passed into with -ldflags54var LibraryRepository string55var logger *logrus.Entry56var secrets []string57// Entry returns the logger entry or creates one if none is present.58func Entry() *logrus.Entry {59 if logger == nil {60 logger = logrus.WithField("library", LibraryRepository)61 logger.Logger.SetFormatter(&PiperLogFormatter{})62 }63 return logger64}65// Writer returns an io.Writer into which a tool's output can be redirected.66func Writer() io.Writer {67 return &logrusWriter{logger: Entry()}68}69// SetVerbose sets the log level with respect to verbose flag.70func SetVerbose(verbose bool) {71 if verbose {72 //Logger().Debugf("logging set to level: %s", level)73 logrus.SetLevel(logrus.DebugLevel)74 }75}76// SetFormatter specifies the log format to use for piper's output77func SetFormatter(logFormat string) {78 Entry().Logger.SetFormatter(&PiperLogFormatter{logFormat: logFormat})79}80// SetStepName sets the stepName field.81func SetStepName(stepName string) {82 logger = Entry().WithField("stepName", stepName)83}84// DeferExitHandler registers a logrus exit handler to allow cleanup activities.85func DeferExitHandler(handler func()) {86 logrus.DeferExitHandler(handler)87}88// RegisterHook registers a logrus hook89func RegisterHook(hook logrus.Hook) {90 logrus.AddHook(hook)91}92func RegisterSecret(secret string) {93 if len(secret) > 0 {94 secrets = append(secrets, secret)95 }...
Step
Using AI Code Generation
1import (2func FeatureContext(s *godog.Suite) {3 s.Step(`^I have (\d+) cukes in my belly$`, iHaveCukesInMyBelly)4 s.Step(`^I wait (\d+) hour$`, iWaitHour)5}6func iHaveCukesInMyBelly(arg1 int) error {7}8func iWaitHour(arg1 int) error {9}
Step
Using AI Code Generation
1import (2func aFeatureFile() error {3}4func aStep() error {5}6func FeatureContext(s *godog.Suite) {7 s.Step(`^a feature file$`, aFeatureFile)8 s.Step(`^a step$`, aStep)9}10func main() {11 opts := godog.Options{12 Output: colors.Colored(os.Stdout),13 Paths: []string{"features"},14 }15 godog.BindCommandLineFlags("godog.", &opts)16 status := godog.TestSuite{17 }.Run()18 if st := m.Run(); st > status {19 }20 os.Exit(status)21}22import (23func aFeatureFile() error {24}25func aStep() error {26}27func FeatureContext(s *godog.Suite) {28 s.Step(`^a feature file$`, aFeatureFile)29 s.Step(`^a step$`, aStep)30}31func main() {32 opts := godog.Options{33 Output: colors.Colored(os.Stdout),34 Paths: []string{"features"},35 }36 godog.BindCommandLineFlags("godog.", &opts)37 status := godog.TestSuite{38 }.Run()39 if st := m.Run(); st > status {40 }41 os.Exit(status)42}
Step
Using AI Code Generation
1import (2func main() {3 f := new(Formatter)4 f.Step("Hello")5 f.Step("World")6}7import (8func main() {9 f := new(Formatter)10 f.Step("Hello")11 f.Step("World")12}13import (14func main() {15 f := new(Formatter)16 f.Step("Hello")17 f.Step("World")18}19import (20func main() {21 f := new(Formatter)22 f.Step("Hello")23 f.Step("World")24}25import (26func main() {27 f := new(Formatter)28 f.Step("Hello")29 f.Step("World")30}31import (32func main() {33 f := new(Formatter)34 f.Step("Hello")35 f.Step("World")36}37import (38func main() {39 f := new(Formatter)40 f.Step("Hello")41 f.Step("World")42}43import (44func main() {45 f := new(Formatter)46 f.Step("Hello")47 f.Step("World")48}49import (50func main() {51 f := new(Formatter)52 f.Step("Hello")53 f.Step("World")54}55import (56func main() {57 f := new(Formatter)58 f.Step("Hello")59 f.Step("World")60}61import (62func main() {63 f := new(Formatter)64 f.Step("Hello")65 f.Step("World
Step
Using AI Code Generation
1import (2func main() {3 reader := bufio.NewReader(os.Stdin)4 fmt.Println("Enter a number:")5 text, _ := reader.ReadString('6 text = strings.TrimSuffix(text, "7 n, _ := strconv.Atoi(text)8 f := NewFormatter()9 f.Step(n)10}11import "fmt"12type Formatter struct {13}14func NewFormatter() *Formatter {15 return &Formatter{}16}17func (f *Formatter) Step(n int) {18 for i := 1; i <= n; i++ {19 for j := 1; j <= n; j++ {
Step
Using AI Code Generation
1import (2func main() {3 fmt.Println("Welcome to the world of Go!")4 fmt.Println("Go is a compiled language!")5 fmt.Println("It is easy to learn Go!")6 time.Sleep(2 * time.Second)7 fmt.Println("Go is a fast language!")8 time.Sleep(2 * time.Second)9 fmt.Println("Go is a concurrent language!")10 time.Sleep(2 * time.Second)11}12import (13func main() {14 fmt.Println("Welcome to the world of Go!")15 fmt.Println("Go is a compiled language!")16 fmt.Println("It is easy to learn Go!")17 time.Sleep(2 * time.Second)18 fmt.Println("Go is a fast language!")19 time.Sleep(2 * time.Second)20 fmt.Println("
Step
Using AI Code Generation
1import "fmt"2func main() {3 f = new(fmt.State)4 f.Format(nil, 0)5 f.Format(nil, 0)6}7import "fmt"8func main() {9 f = new(fmt.State)10 f.Format(nil, 0)11 f.Format(nil, 0)12}13 0x0000 00000 (1.go:5) TEXT "".main(SB), ABIInternal, $0-014 0x0000 00000 (1.go:5) FUNCDATA $0, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)15 0x0000 00000 (1.go:5) FUNCDATA $1, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB)16 0x0000 00000 (1.go:6) MOVQ (TLS), CX17 0x0009 00009 (1.go:6) CMPQ SP, 16(CX)18 0x000d 00013 (1.go:6) JLS 4619 0x000f 00015 (1.go:6) SUBQ $24, SP20 0x0013 00019 (1.go:6) MOVQ BP, 16(SP)21 0x0018 00024 (1.go:6) LEAQ 16(SP), BP22 0x001d 00029 (1.go:6) FUNCDATA $3, "".main.stkobj(SB)23 0x001d 00029 (1.go:7) MOVQ $0, "".f+8(SP)24 0x0027 00039 (1.go:7) MOVQ
Step
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println(s)4 fmt.Println("Hello, World!")5 fmt.Printf("Hello, World!")6 fmt.Printf("%s", s)7}8import "fmt"9func main() {10 fmt.Println(s)11 fmt.Println("Hello, World!")12 fmt.Printf("Hello, World!")13 fmt.Printf("%s", s)14}15import "fmt"16func main() {17 fmt.Println(s)18 fmt.Println("Hello, World!")19 fmt.Printf("Hello, World!")20 fmt.Printf("%s", s)21}22import "fmt"23func main() {24 fmt.Println(s)25 fmt.Println("Hello, World!")26 fmt.Printf("Hello, World!")27 fmt.Printf("%s", s)28}29import "fmt"30func main() {31 fmt.Println(s)32 fmt.Println("Hello, World!")33 fmt.Printf("Hello, World!")34 fmt.Printf("%s", s)35}36import "fmt"37func main() {38 fmt.Println(s)39 fmt.Println("Hello, World!")40 fmt.Printf("Hello, World!")41 fmt.Printf("%s", s)42}43import "fmt"44func main() {45 fmt.Println(s)46 fmt.Println("Hello, World!")47 fmt.Printf("Hello, World!")48 fmt.Printf("%s", s)49}50import "fmt"51func main() {52 fmt.Println(s)53 fmt.Println("Hello, World!")54 fmt.Printf("
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!