Best Gauge code snippet using logger.logInfo
ze.go
Source:ze.go
...12 "github.com/gotomicro/dmgo/util"13)14type logFilter struct{}15func (filter *logFilter) DmDriverOpen(filterChain *filterChain, d *Driver, dsn string) (ret *Connection, err error) {16 var logRecord = d.logInfo.logRecord17 logRecord.Set(d, "open", dsn)18 defer func() {19 filter.doLog(logRecord)20 }()21 ret, err = filterChain.DmDriverOpen(d, dsn)22 if err != nil {23 logRecord.SetError(err)24 return25 }26 logRecord.SetReturnValue(ret)27 return28}29func (filter *logFilter) DmDriverOpenConnector(filterChain *filterChain, d *Driver, dsn string) (ret *Connector, err error) {30 var logRecord = d.logInfo.logRecord31 logRecord.Set(d, "openConnector", dsn)32 defer func() {33 filter.doLog(logRecord)34 }()35 ret, err = filterChain.DmDriverOpenConnector(d, dsn)36 if err != nil {37 logRecord.SetError(err)38 return39 }40 logRecord.SetReturnValue(ret)41 return42}43func (filter *logFilter) DmConnectorConnect(filterChain *filterChain, c *Connector, ctx context.Context) (ret *Connection, err error) {44 var logRecord = c.logInfo.logRecord45 logRecord.Set(c, "connect")46 defer func() {47 filter.doLog(logRecord)48 }()49 ret, err = filterChain.DmConnectorConnect(c, ctx)50 if err != nil {51 logRecord.SetError(err)52 return53 }54 logRecord.SetReturnValue(ret)55 return56}57func (filter *logFilter) DmConnectorDriver(filterChain *filterChain, c *Connector) (ret *Driver) {58 var logRecord = c.logInfo.logRecord59 logRecord.Set(c, "driver")60 defer func() {61 filter.doLog(logRecord)62 }()63 ret = filterChain.DmConnectorDriver(c)64 logRecord.SetReturnValue(ret)65 return66}67func (filter *logFilter) DmConnectionBegin(filterChain *filterChain, c *Connection) (ret *Connection, err error) {68 var logRecord = c.logInfo.logRecord69 logRecord.Set(c, "begin")70 defer func() {71 filter.doLog(logRecord)72 }()73 ret, err = filterChain.DmConnectionBegin(c)74 if err != nil {75 logRecord.SetError(err)76 return77 }78 logRecord.SetReturnValue(ret)79 return80}81func (filter *logFilter) DmConnectionBeginTx(filterChain *filterChain, c *Connection, ctx context.Context, opts driver.TxOptions) (ret *Connection, err error) {82 var logRecord = c.logInfo.logRecord83 logRecord.Set(c, "beginTx", opts)84 defer func() {85 filter.doLog(logRecord)86 }()87 ret, err = filterChain.DmConnectionBeginTx(c, ctx, opts)88 if err != nil {89 logRecord.SetError(err)90 return91 }92 logRecord.SetReturnValue(ret)93 return94}95func (filter *logFilter) DmConnectionCommit(filterChain *filterChain, c *Connection) (err error) {96 var logRecord = c.logInfo.logRecord97 logRecord.Set(c, "commit")98 defer func() {99 filter.doLog(logRecord)100 }()101 err = filterChain.DmConnectionCommit(c)102 if err != nil {103 logRecord.SetError(err)104 return105 }106 return107}108func (filter *logFilter) DmConnectionRollback(filterChain *filterChain, c *Connection) (err error) {109 var logRecord = c.logInfo.logRecord110 logRecord.Set(c, "rollback")111 defer func() {112 filter.doLog(logRecord)113 }()114 err = filterChain.DmConnectionRollback(c)115 if err != nil {116 logRecord.SetError(err)117 return118 }119 return120}121func (filter *logFilter) DmConnectionClose(filterChain *filterChain, c *Connection) (err error) {122 var logRecord = c.logInfo.logRecord123 logRecord.Set(c, "close")124 defer func() {125 filter.doLog(logRecord)126 }()127 err = filterChain.DmConnectionClose(c)128 if err != nil {129 logRecord.SetError(err)130 return131 }132 return133}134func (filter *logFilter) DmConnectionPing(filterChain *filterChain, c *Connection, ctx context.Context) (err error) {135 var logRecord = c.logInfo.logRecord136 logRecord.Set(c, "ping")137 defer func() {138 filter.doLog(logRecord)139 }()140 err = filterChain.DmConnectionPing(c, ctx)141 if err != nil {142 logRecord.SetError(err)143 return144 }145 return146}147func (filter *logFilter) DmConnectionExec(filterChain *filterChain, c *Connection, query string, args []driver.Value) (ret *DmResult, err error) {148 var logRecord = c.logInfo.logRecord149 logRecord.Set(c, "executeByStmt", query, args)150 defer func() {151 filter.executeAfter(c.logInfo, logRecord)152 filter.doLog(logRecord)153 }()154 logRecord.SetSql(query)155 filter.executeBefore(c.logInfo)156 ret, err = filterChain.DmConnectionExec(c, query, args)157 if err != nil {158 logRecord.SetError(err)159 return160 }161 logRecord.SetReturnValue(ret)162 return163}164func (filter *logFilter) DmConnectionExecContext(filterChain *filterChain, c *Connection, ctx context.Context, query string, args []driver.NamedValue) (ret *DmResult, err error) {165 var logRecord = c.logInfo.logRecord166 logRecord.Set(c, "executeCtx", query, args)167 defer func() {168 filter.executeAfter(c.logInfo, logRecord)169 filter.doLog(logRecord)170 }()171 logRecord.SetSql(query)172 filter.executeBefore(c.logInfo)173 ret, err = filterChain.DmConnectionExecContext(c, ctx, query, args)174 if err != nil {175 logRecord.SetError(err)176 return177 }178 logRecord.SetReturnValue(ret)179 return180}181func (filter *logFilter) DmConnectionQuery(filterChain *filterChain, c *Connection, query string, args []driver.Value) (ret *DmRows, err error) {182 var logRecord = c.logInfo.logRecord183 logRecord.Set(c, "query", query, args)184 defer func() {185 filter.executeAfter(c.logInfo, logRecord)186 filter.doLog(logRecord)187 }()188 logRecord.SetSql(query)189 filter.executeBefore(c.logInfo)190 ret, err = filterChain.DmConnectionQuery(c, query, args)191 if err != nil {192 logRecord.SetError(err)193 return194 }195 logRecord.SetReturnValue(ret)196 return197}198func (filter *logFilter) DmConnectionQueryContext(filterChain *filterChain, c *Connection, ctx context.Context, query string, args []driver.NamedValue) (ret *DmRows, err error) {199 var logRecord = c.logInfo.logRecord200 logRecord.Set(c, "queryCtx", query, args)201 defer func() {202 filter.executeAfter(c.logInfo, logRecord)203 filter.doLog(logRecord)204 }()205 logRecord.SetSql(query)206 filter.executeBefore(c.logInfo)207 ret, err = filterChain.DmConnectionQueryContext(c, ctx, query, args)208 if err != nil {209 logRecord.SetError(err)210 return211 }212 logRecord.SetReturnValue(ret)213 return214}215func (filter *logFilter) DmConnectionPrepare(filterChain *filterChain, c *Connection, query string) (ret *DmStatement, err error) {216 var logRecord = c.logInfo.logRecord217 logRecord.Set(c, "prepareStatement", query)218 defer func() {219 filter.doLog(logRecord)220 }()221 logRecord.SetSql(query)222 ret, err = filterChain.DmConnectionPrepare(c, query)223 if err != nil {224 logRecord.SetError(err)225 return226 }227 logRecord.SetReturnValue(ret)228 return229}230func (filter *logFilter) DmConnectionPrepareContext(filterChain *filterChain, c *Connection, ctx context.Context, query string) (ret *DmStatement, err error) {231 var logRecord = c.logInfo.logRecord232 logRecord.Set(c, "prepareStatementCtx", query)233 defer func() {234 filter.doLog(logRecord)235 }()236 logRecord.SetSql(query)237 ret, err = filterChain.DmConnectionPrepareContext(c, ctx, query)238 if err != nil {239 logRecord.SetError(err)240 return241 }242 logRecord.SetReturnValue(ret)243 return244}245func (filter *logFilter) DmConnectionResetSession(filterChain *filterChain, c *Connection, ctx context.Context) (err error) {246 var logRecord = c.logInfo.logRecord247 logRecord.Set(c, "resetSession")248 defer func() {249 filter.doLog(logRecord)250 }()251 err = filterChain.DmConnectionResetSession(c, ctx)252 if err != nil {253 logRecord.SetError(err)254 return255 }256 return257}258func (filter *logFilter) DmConnectionCheckNamedValue(filterChain *filterChain, c *Connection, nv *driver.NamedValue) (err error) {259 var logRecord = c.logInfo.logRecord260 logRecord.Set(c, "checkNamedValue", nv)261 defer func() {262 filter.doLog(logRecord)263 }()264 err = filterChain.DmConnectionCheckNamedValue(c, nv)265 if err != nil {266 logRecord.SetError(err)267 return268 }269 return270}271func (filter *logFilter) DmStatementClose(filterChain *filterChain, s *DmStatement) (err error) {272 var logRecord = s.logInfo.logRecord273 logRecord.Set(s, "close")274 defer func() {275 filter.doLog(logRecord)276 }()277 err = filterChain.DmStatementClose(s)278 if err != nil {279 logRecord.SetError(err)280 return281 }282 return283}284func (filter *logFilter) DmStatementNumInput(filterChain *filterChain, s *DmStatement) (ret int) {285 var logRecord = s.logInfo.logRecord286 logRecord.Set(s, "numInput")287 defer func() {288 filter.doLog(logRecord)289 }()290 ret = filterChain.DmStatementNumInput(s)291 logRecord.SetReturnValue(ret)292 return293}294func (filter *logFilter) DmStatementExec(filterChain *filterChain, s *DmStatement, args []driver.Value) (ret *DmResult, err error) {295 var logRecord = s.logInfo.logRecord296 logRecord.Set(s, "executeByStmt", args)297 defer func() {298 filter.executeAfter(s.logInfo, logRecord)299 filter.doLog(logRecord)300 }()301 logRecord.SetSql(s.nativeSql)302 filter.executeBefore(s.logInfo)303 ret, err = filterChain.DmStatementExec(s, args)304 if err != nil {305 logRecord.SetError(err)306 return307 }308 logRecord.SetReturnValue(ret)309 return310}311func (filter *logFilter) DmStatementExecContext(filterChain *filterChain, s *DmStatement, ctx context.Context, args []driver.NamedValue) (ret *DmResult, err error) {312 var logRecord = s.logInfo.logRecord313 logRecord.Set(s, "executeCtx", args)314 defer func() {315 filter.executeAfter(s.logInfo, logRecord)316 filter.doLog(logRecord)317 }()318 logRecord.SetSql(s.nativeSql)319 filter.executeBefore(s.logInfo)320 ret, err = filterChain.DmStatementExecContext(s, ctx, args)321 if err != nil {322 logRecord.SetError(err)323 return324 }325 logRecord.SetReturnValue(ret)326 return327}328func (filter *logFilter) DmStatementQuery(filterChain *filterChain, s *DmStatement, args []driver.Value) (ret *DmRows, err error) {329 var logRecord = s.logInfo.logRecord330 logRecord.Set(s, "query", args)331 defer func() {332 filter.executeAfter(s.logInfo, logRecord)333 filter.doLog(logRecord)334 }()335 logRecord.SetSql(s.nativeSql)336 filter.executeBefore(s.logInfo)337 ret, err = filterChain.DmStatementQuery(s, args)338 if err != nil {339 logRecord.SetError(err)340 return341 }342 logRecord.SetReturnValue(ret)343 return344}345func (filter *logFilter) DmStatementQueryContext(filterChain *filterChain, s *DmStatement, ctx context.Context, args []driver.NamedValue) (ret *DmRows, err error) {346 var logRecord = s.logInfo.logRecord347 logRecord.Set(s, "queryCtx", args)348 defer func() {349 filter.executeAfter(s.logInfo, logRecord)350 filter.doLog(logRecord)351 }()352 logRecord.SetSql(s.nativeSql)353 filter.executeBefore(s.logInfo)354 ret, err = filterChain.DmStatementQueryContext(s, ctx, args)355 if err != nil {356 logRecord.SetError(err)357 return358 }359 logRecord.SetReturnValue(ret)360 return361}362func (filter *logFilter) DmStatementCheckNamedValue(filterChain *filterChain, s *DmStatement, nv *driver.NamedValue) (err error) {363 var logRecord = s.logInfo.logRecord364 logRecord.Set(s, "checkNamedValue", nv)365 defer func() {366 filter.doLog(logRecord)367 }()368 err = filterChain.DmStatementCheckNamedValue(s, nv)369 if err != nil {370 logRecord.SetError(err)371 return372 }373 return374}375func (filter *logFilter) DmResultLastInsertId(filterChain *filterChain, r *DmResult) (ret int64, err error) {376 var logRecord = r.logInfo.logRecord377 logRecord.Set(r, "lastInsertId")378 defer func() {379 filter.doLog(logRecord)380 }()381 ret, err = filterChain.DmResultLastInsertId(r)382 if err != nil {383 logRecord.SetError(err)384 return385 }386 logRecord.SetReturnValue(ret)387 return388}389func (filter *logFilter) DmResultRowsAffected(filterChain *filterChain, r *DmResult) (ret int64, err error) {390 var logRecord = r.logInfo.logRecord391 logRecord.Set(r, "rowsAffected")392 defer func() {393 filter.doLog(logRecord)394 }()395 ret, err = filterChain.DmResultRowsAffected(r)396 if err != nil {397 logRecord.SetError(err)398 return399 }400 logRecord.SetReturnValue(ret)401 return402}403func (filter *logFilter) DmRowsColumns(filterChain *filterChain, r *DmRows) (ret []string) {404 var logRecord = r.logInfo.logRecord405 logRecord.Set(r, "columns")406 defer func() {407 filter.doLog(logRecord)408 }()409 ret = filterChain.DmRowsColumns(r)410 logRecord.SetReturnValue(ret)411 return412}413func (filter *logFilter) DmRowsClose(filterChain *filterChain, r *DmRows) (err error) {414 var logRecord = r.logInfo.logRecord415 logRecord.Set(r, "close")416 defer func() {417 filter.doLog(logRecord)418 }()419 err = filterChain.DmRowsClose(r)420 if err != nil {421 logRecord.SetError(err)422 return423 }424 return425}426func (filter *logFilter) DmRowsNext(filterChain *filterChain, r *DmRows, dest []driver.Value) (err error) {427 var logRecord = r.logInfo.logRecord428 logRecord.Set(r, "next", dest)429 defer func() {430 filter.doLog(logRecord)431 }()432 err = filterChain.DmRowsNext(r, dest)433 if err != nil {434 logRecord.SetError(err)435 return436 }437 return438}439func (filter *logFilter) DmRowsHasNextResultSet(filterChain *filterChain, r *DmRows) (ret bool) {440 var logRecord = r.logInfo.logRecord441 logRecord.Set(r, "hasNextResultSet")442 defer func() {443 filter.doLog(logRecord)444 }()445 ret = filterChain.DmRowsHasNextResultSet(r)446 logRecord.SetReturnValue(ret)447 return448}449func (filter *logFilter) DmRowsNextResultSet(filterChain *filterChain, r *DmRows) (err error) {450 var logRecord = r.logInfo.logRecord451 logRecord.Set(r, "nextResultSet")452 defer func() {453 filter.doLog(logRecord)454 }()455 err = filterChain.DmRowsNextResultSet(r)456 if err != nil {457 logRecord.SetError(err)458 return459 }460 return461}462func (filter *logFilter) DmRowsColumnTypeScanType(filterChain *filterChain, r *DmRows, index int) (ret reflect.Type) {463 var logRecord = r.logInfo.logRecord464 logRecord.Set(r, "columnTypeScanType", index)465 defer func() {466 filter.doLog(logRecord)467 }()468 ret = filterChain.DmRowsColumnTypeScanType(r, index)469 logRecord.SetReturnValue(ret)470 return471}472func (filter *logFilter) DmRowsColumnTypeDatabaseTypeName(filterChain *filterChain, r *DmRows, index int) (ret string) {473 var logRecord = r.logInfo.logRecord474 logRecord.Set(r, "columnTypeDatabaseTypeName", index)475 defer func() {476 filter.doLog(logRecord)477 }()478 ret = filterChain.DmRowsColumnTypeDatabaseTypeName(r, index)479 logRecord.SetReturnValue(ret)480 return481}482func (filter *logFilter) DmRowsColumnTypeLength(filterChain *filterChain, r *DmRows, index int) (length int64, ok bool) {483 var logRecord = r.logInfo.logRecord484 logRecord.Set(r, "columnTypeLength", index)485 defer func() {486 filter.doLog(logRecord)487 }()488 length, ok = filterChain.DmRowsColumnTypeLength(r, index)489 if ok {490 logRecord.SetReturnValue(length)491 } else {492 logRecord.SetReturnValue(-1)493 }494 return495}496func (filter *logFilter) DmRowsColumnTypeNullable(filterChain *filterChain, r *DmRows, index int) (nullable, ok bool) {497 var logRecord = r.logInfo.logRecord498 logRecord.Set(r, "columnTypeNullable", index)499 defer func() {500 filter.doLog(logRecord)501 }()502 nullable, ok = filterChain.DmRowsColumnTypeNullable(r, index)503 if ok {504 logRecord.SetReturnValue(nullable)505 } else {506 logRecord.SetReturnValue(false)507 }508 return509}510func (filter *logFilter) DmRowsColumnTypePrecisionScale(filterChain *filterChain, r *DmRows, index int) (precision, scale int64, ok bool) {511 var logRecord = r.logInfo.logRecord512 logRecord.Set(r, "columnTypePrecisionScale", index)513 defer func() {514 filter.doLog(logRecord)515 }()516 precision, scale, ok = filterChain.DmRowsColumnTypePrecisionScale(r, index)517 if ok {518 logRecord.SetReturnValue(strconv.FormatInt(precision, 10) + "&" + strconv.FormatInt(scale, 10))519 } else {520 logRecord.SetReturnValue("-1&-1")521 }522 return523}524func (filter *logFilter) executeBefore(logInfo *logInfo) {525 if LogFilterLogger.IsSqlEnabled() {526 logInfo.lastExecuteStartNano = time.Now()527 }528}529func (filter *logFilter) executeAfter(logInfo *logInfo, record *LogRecord) {530 if LogFilterLogger.IsSqlEnabled() {531 record.SetUsedTime(time.Since(logInfo.lastExecuteStartNano))532 }533}534func (filter *logFilter) doLog(record *LogRecord) {535 if record == nil {536 return537 }538 if record.GetError() != nil {539 LogFilterLogger.ErrorWithErr(record.ToString(), record.GetError())540 } else if record.GetSql() != "" && LogFilterLogger.IsSqlEnabled() {541 LogFilterLogger.Sql(record.ToString())542 } else {543 LogFilterLogger.Info(record.ToString())544 }545}546/************************************************************************************************************/547type Logger struct {548}549var LogFilterLogger = &Logger{}550var ConnLogger = &Logger{}551var AccessLogger = &Logger{}552func (logger Logger) IsDebugEnabled() bool {553 return LogLevel >= LOG_DEBUG554}555func (logger Logger) IsErrorEnabled() bool {556 return LogLevel >= LOG_ERROR557}558func (logger Logger) IsInfoEnabled() bool {559 return LogLevel >= LOG_INFO560}561func (logger Logger) IsWarnEnabled() bool {562 return LogLevel >= LOG_WARN563}564func (logger Logger) IsSqlEnabled() bool {565 return LogLevel >= LOG_SQL566}567func (logger Logger) Debug(msg string) {568 if logger.IsDebugEnabled() {569 logger.println(logger.formatHead("DEBUG") + msg)570 }571}572func (logger Logger) DebugWithErr(msg string, err error) {573 if logger.IsDebugEnabled() {574 if e, ok := err.(*DmError); ok {575 logger.println(logger.formatHead("DEBUG") + msg + util.LINE_SEPARATOR + e.FormatStack())576 } else {577 logger.println(logger.formatHead("DEBUG") + msg + util.LINE_SEPARATOR + err.Error())578 }579 }580}581func (logger Logger) Info(msg string) {582 if logger.IsInfoEnabled() {583 logger.println(logger.formatHead("INFO ") + msg)584 }585}586func (logger Logger) Sql(msg string) {587 if logger.IsSqlEnabled() {588 logger.println(logger.formatHead("SQL ") + msg)589 }590}591func (logger Logger) Warn(msg string) {592 if logger.IsWarnEnabled() {593 logger.println(logger.formatHead("WARN ") + msg)594 }595}596func (logger Logger) ErrorWithErr(msg string, err error) {597 if e, ok := err.(*DmError); ok {598 logger.println(logger.formatHead("ERROR") + msg + util.LINE_SEPARATOR + e.FormatStack())599 } else {600 logger.println(logger.formatHead("ERROR") + msg + util.LINE_SEPARATOR + err.Error())601 }602}603//TODO: è·ågoroutine objId604func (logger Logger) formatHead(head string) string {605 // return "[" + head + " - " + StringUtil.formatTime() + "] tid:" + Thread.currentThread().getId();606 return "[" + head + " - " + util.StringUtil.FormatTime() + "]"607}608func (logger Logger) println(msg string) {609 goMap["log"].(*logWriter).WriteLine(msg)610}611/*************************************************************************************************/612func formatSource(source interface{}) string {613 if source == nil {614 return ""615 }616 var str string617 switch src := source.(type) {618 case string:619 str += src620 case *Driver:621 str += formatDriver(src)622 case *Connector:623 str += formatContor(src)624 case *Connection:625 str += formatConn(src)626 case *DmStatement:627 str += formatConn(src.dmConn) + ", "628 str += formatStmt(src)629 case *DmResult:630 str += formatConn(src.dmStmt.dmConn) + ", "631 str += formatStmt(src.dmStmt) + ", "632 str += formatRs(src)633 case *DmRows:634 str += formatConn(src.CurrentRows.dmStmt.dmConn) + ", "635 str += formatStmt(src.CurrentRows.dmStmt) + ", "636 str += formatRows(src)637 default:638 str += reflect.TypeOf(src).String() + "@" + reflect.ValueOf(src).Addr().String()639 }640 return str641}642func formatDriver(driver *Driver) string {643 if driver != nil && driver.logInfo != nil {644 return "driver-" + strconv.FormatInt(driver.getID(), 10)645 }646 return "driver-nil"647}648func formatContor(contor *Connector) string {649 if contor != nil && contor.logInfo != nil {650 return "contor-" + strconv.FormatInt(contor.getID(), 10)651 }652 return "contor-nil"653}654func formatConn(conn *Connection) string {655 if conn != nil && conn.logInfo != nil {656 return "conn-" + strconv.FormatInt(conn.getID(), 10)657 }658 return "conn-nil"659}660func formatStmt(stmt *DmStatement) string {661 if stmt != nil && stmt.logInfo != nil {662 return "stmt-" + strconv.FormatInt(stmt.getID(), 10)663 }664 return "stmt-nil"665}666func formatRs(result *DmResult) string {667 if result != nil && result.logInfo != nil {668 return "rs-" + strconv.FormatInt(result.getID(), 10)669 }670 return "rs-nil"671}672func formatRows(rows *DmRows) string {673 if rows != nil && rows.logInfo != nil {674 return "rows-" + strconv.FormatInt(rows.getID(), 10)675 }676 return "rows-nil"677}678func formatTrace(source string, method string, returnValue interface{}, params ...interface{}) string {679 var str string680 if source != "" {681 str += "{ " + source + " } "682 }683 str += method + "("684 var paramStartIndex = 0685 if params != nil && len(params) > paramStartIndex {686 for i := paramStartIndex; i < len(params); i++ {687 if i != paramStartIndex {...
log_test.go
Source:log_test.go
...15 "github.com/go-logr/logr"16 . "github.com/onsi/ginkgo"17 . "github.com/onsi/gomega"18)19// logInfo is the information for a particular fakeLogger message20type logInfo struct {21 name []string22 tags []interface{}23 msg string24}25// fakeLoggerRoot is the root object to which all fakeLoggers record their messages.26type fakeLoggerRoot struct {27 messages []logInfo28}29// fakeLogger is a fake implementation of logr.Logger that records30// messages, tags, and names,31// just records the name.32type fakeLogger struct {33 name []string34 tags []interface{}35 root *fakeLoggerRoot36}37func (f *fakeLogger) WithName(name string) logr.Logger {38 names := append([]string(nil), f.name...)39 names = append(names, name)40 return &fakeLogger{41 name: names,42 tags: f.tags,43 root: f.root,44 }45}46func (f *fakeLogger) WithValues(vals ...interface{}) logr.Logger {47 tags := append([]interface{}(nil), f.tags...)48 tags = append(tags, vals...)49 return &fakeLogger{50 name: f.name,51 tags: tags,52 root: f.root,53 }54}55func (f *fakeLogger) Error(err error, msg string, vals ...interface{}) {56 tags := append([]interface{}(nil), f.tags...)57 tags = append(tags, "error", err)58 tags = append(tags, vals...)59 f.root.messages = append(f.root.messages, logInfo{60 name: append([]string(nil), f.name...),61 tags: tags,62 msg: msg,63 })64}65func (f *fakeLogger) Info(msg string, vals ...interface{}) {66 tags := append([]interface{}(nil), f.tags...)67 tags = append(tags, vals...)68 f.root.messages = append(f.root.messages, logInfo{69 name: append([]string(nil), f.name...),70 tags: tags,71 msg: msg,72 })73}74func (f *fakeLogger) Enabled() bool { return true }75func (f *fakeLogger) V(lvl int) logr.InfoLogger { return f }76var _ = Describe("logging", func() {77 Describe("top-level logger", func() {78 It("hold newly created loggers until a logger is set", func() {79 By("grabbing a new sub-logger and logging to it")80 l1 := Log.WithName("runtimeLog").WithValues("newtag", "newvalue1")81 l1.Info("before msg")82 By("actually setting the logger")83 logger := &fakeLogger{root: &fakeLoggerRoot{}}84 SetLogger(logger)85 By("grabbing another sub-logger and logging to both loggers")86 l2 := Log.WithName("runtimeLog").WithValues("newtag", "newvalue2")87 l1.Info("after msg 1")88 l2.Info("after msg 2")89 By("ensuring that messages after the logger was set were logged")90 Expect(logger.root.messages).To(ConsistOf(91 logInfo{name: []string{"runtimeLog"}, tags: []interface{}{"newtag", "newvalue1"}, msg: "after msg 1"},92 logInfo{name: []string{"runtimeLog"}, tags: []interface{}{"newtag", "newvalue2"}, msg: "after msg 2"},93 ))94 })95 })96 Describe("lazy logger initialization", func() {97 var (98 root *fakeLoggerRoot99 baseLog logr.Logger100 delegLog *DelegatingLogger101 )102 BeforeEach(func() {103 root = &fakeLoggerRoot{}104 baseLog = &fakeLogger{root: root}105 delegLog = NewDelegatingLogger(NullLogger{})106 })107 It("should delegate with name", func() {108 By("asking for a logger with a name before fulfill, and logging")109 befFulfill1 := delegLog.WithName("before-fulfill")110 befFulfill2 := befFulfill1.WithName("two")111 befFulfill1.Info("before fulfill")112 By("logging on the base logger before fulfill")113 delegLog.Info("before fulfill base")114 By("ensuring that no messages were actually recorded")115 Expect(root.messages).To(BeEmpty())116 By("fulfilling the promise")117 delegLog.Fulfill(baseLog)118 By("logging with the existing loggers after fulfilling")119 befFulfill1.Info("after 1")120 befFulfill2.Info("after 2")121 By("grabbing a new sub-logger of a previously constructed logger and logging to it")122 befFulfill1.WithName("after-from-before").Info("after 3")123 By("logging with new loggers")124 delegLog.WithName("after-fulfill").Info("after 4")125 By("ensuring that the messages are appropriately named")126 Expect(root.messages).To(ConsistOf(127 logInfo{name: []string{"before-fulfill"}, msg: "after 1"},128 logInfo{name: []string{"before-fulfill", "two"}, msg: "after 2"},129 logInfo{name: []string{"before-fulfill", "after-from-before"}, msg: "after 3"},130 logInfo{name: []string{"after-fulfill"}, msg: "after 4"},131 ))132 })133 It("should delegate with tags", func() {134 By("asking for a logger with a name before fulfill, and logging")135 befFulfill1 := delegLog.WithValues("tag1", "val1")136 befFulfill2 := befFulfill1.WithValues("tag2", "val2")137 befFulfill1.Info("before fulfill")138 By("logging on the base logger before fulfill")139 delegLog.Info("before fulfill base")140 By("ensuring that no messages were actually recorded")141 Expect(root.messages).To(BeEmpty())142 By("fulfilling the promise")143 delegLog.Fulfill(baseLog)144 By("logging with the existing loggers after fulfilling")145 befFulfill1.Info("after 1")146 befFulfill2.Info("after 2")147 By("grabbing a new sub-logger of a previously constructed logger and logging to it")148 befFulfill1.WithValues("tag3", "val3").Info("after 3")149 By("logging with new loggers")150 delegLog.WithValues("tag3", "val3").Info("after 4")151 By("ensuring that the messages are appropriately named")152 Expect(root.messages).To(ConsistOf(153 logInfo{tags: []interface{}{"tag1", "val1"}, msg: "after 1"},154 logInfo{tags: []interface{}{"tag1", "val1", "tag2", "val2"}, msg: "after 2"},155 logInfo{tags: []interface{}{"tag1", "val1", "tag3", "val3"}, msg: "after 3"},156 logInfo{tags: []interface{}{"tag3", "val3"}, msg: "after 4"},157 ))158 })159 It("shouldn't fulfill twice", func() {160 By("fulfilling once")161 delegLog.Fulfill(baseLog)162 By("logging a bit")163 delegLog.Info("msg 1")164 By("fulfilling with a new logger")165 delegLog.Fulfill(&fakeLogger{})166 By("logging some more")167 delegLog.Info("msg 2")168 By("checking that all log messages are present")169 Expect(root.messages).To(ConsistOf(170 logInfo{msg: "msg 1"},171 logInfo{msg: "msg 2"},172 ))173 })174 })175})...
logger.go
Source:logger.go
...28func (logger *Logger) UnaryServerInterceptor() grpc.UnaryServerInterceptor {29 return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {30 start := time.Now()31 resp, err = handler(ctx, req)32 logInfo := logger.infoPool.Get().(models.LoggerInfo)33 logInfo.StartTime = start.Format(LoggerDefaultDateFormat)34 logInfo.Status = 20035 logInfo.Duration = strconv.FormatInt(time.Since(start).Milliseconds(), 10)36 logInfo.HostName = "grpc"37 logInfo.Method = "unary"38 logInfo.Path = info.FullMethod39 logInfo.Request = req40 logInfo.Response = resp41 statusColor := logInfo.StatusCodeColor()42 methodColor := logInfo.MethodColor()43 resetColor := logInfo.ResetColor()44 outLog := fmt.Sprintf("status: %s %3d %s| %5v ms| %s |%s %5s %s | %s | request: %v | response: %v",45 statusColor, logInfo.Status, resetColor,46 logInfo.Duration,47 logInfo.HostName,48 methodColor, logInfo.Method, resetColor,49 logInfo.Path,50 logInfo.Request,51 logInfo.Response,52 )53 logger.infoPool.Put(logInfo)54 logger.log.Info(outLog)55 return resp, err56 }57}58func (logger *Logger) StreamServerInterceptor() grpc.StreamServerInterceptor {59 return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {60 if strings.HasPrefix(info.FullMethod, "/grpc.reflection") {61 return handler(srv, ss)62 }63 start := time.Now()64 err := handler(srv, ss)65 logInfo := logger.infoPool.Get().(models.LoggerInfo)66 logInfo.StartTime = start.Format(LoggerDefaultDateFormat)67 logInfo.Status = 20068 logInfo.Duration = strconv.FormatInt(time.Since(start).Milliseconds(), 10)69 logInfo.HostName = "grpc"70 logInfo.Method = "stream"71 logInfo.Path = info.FullMethod72 statusColor := logInfo.StatusCodeColor()73 methodColor := logInfo.MethodColor()74 resetColor := logInfo.ResetColor()75 outLog := fmt.Sprintf("status: %s %3d %s| %5v ms| %s |%s %5s %s | %s ",76 statusColor, logInfo.Status, resetColor,77 logInfo.Duration,78 logInfo.HostName,79 methodColor, logInfo.Method, resetColor,80 logInfo.Path,81 )82 logger.infoPool.Put(logInfo)83 logger.log.Info(outLog)84 return err85 }86}...
logInfo
Using AI Code Generation
1import (2func main() {3 f, err := os.OpenFile("logfile.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)4 if err != nil {5 fmt.Println("error opening file: %v", err)6 }7 defer f.Close()8 log.SetOutput(f)9 log.Println("This is a test log entry")10}11import (12func main() {13 f, err := os.OpenFile("logfile.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)14 if err != nil {15 fmt.Println("error opening file: %v", err)16 }17 defer f.Close()18 log.SetOutput(f)19 log.Println("This is a test log entry")20}21import (22func main() {23 f, err := os.OpenFile("logfile.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)24 if err != nil {25 fmt.Println("error opening file: %v", err)26 }27 defer f.Close()28 log.SetOutput(f)29 log.Println("This is a test log entry")30}31import (32func main() {33 f, err := os.OpenFile("logfile.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)34 if err != nil {35 fmt.Println("error opening file: %v", err)36 }37 defer f.Close()38 log.SetOutput(f)39 log.Println("This is a test log entry")40}41import (42func main() {43 f, err := os.OpenFile("logfile.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)44 if err != nil {45 fmt.Println("error opening file: %v", err)46 }47 defer f.Close()48 log.SetOutput(f)49 log.Println("This is a test
logInfo
Using AI Code Generation
1import "logger"2func main() {3 logger.logInfo("message")4}5import "logger"6func main() {7 logger.logError("message")8}9import "logger"10func main() {11 logger.logDebug("message")12}13import "logger"14func main() {15 logger.logWarn("message")16}17import "logger"18func main() {19 logger.logFatal("message")20}21import "logger"22func main() {23 logger.logPanic("message")24}25import "logger"26func main() {27 logger.logTrace("message")28}29import "logger"30func main() {31 logger.log("message")32}33import "logger"34func main() {35 logger.logAll("message")36}37import "logger"38func main() {39 logger.logAll("message")40}41import "logger"42func main() {43 logger.logAll("message")44}45import "logger"46func main() {47 logger.logAll("message")48}49import "logger"50func main() {51 logger.logAll("message")52}53import "logger"54func main() {55 logger.logAll("message
logInfo
Using AI Code Generation
1import "log"2func main() {3 log.Print("Hello, world!")4}5import "log"6func main() {7 log.Print("Hello, world!")8}9import "log"10func main() {11 log.Print("Hello, world!")12}13import "log"14func main() {15 log.Print("Hello, world!")16}17import "log"18func main() {19 log.Print("Hello, world!")20}21import "log"22func main() {23 log.Print("Hello, world!")24}25import "log"26func main() {27 log.Print("Hello, world!")28}29import "log"30func main() {31 log.Print("Hello, world!")32}33import "log"34func main() {35 log.Print("Hello, world!")36}37import "log"38func main() {39 log.Print("Hello, world!")40}41import "log"42func main() {43 log.Print("Hello, world!")44}45import "log"46func main() {47 log.Print("Hello, world!")48}49import "log"50func main() {51 log.Print("Hello, world!")52}53import
logInfo
Using AI Code Generation
1import "log"2import "fmt"3import "os"4func main() {5 logger := log.New(os.Stdout, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)6 logger.Println("This is a log message.")7 fmt.Println("This is a log message.")8}9import "log"10import "fmt"11import "os"12func main() {13 logger := log.New(os.Stdout, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)14 logger.Println("This is a log message.")15 fmt.Println("This is a log message.")16}17import "log"18import "fmt"19import "os"20func main() {21 logger := log.New(os.Stdout, "DEBUG: ", log.Ldate|log.Ltime|log.Lshortfile)22 logger.Println("This is a log message.")23 fmt.Println("This is a log message.")24}25import "log"26import "fmt"27import "os"28func main() {29 logger := log.New(os.Stdout, "WARNING: ", log.Ldate|log.Ltime|log.Lshortfile)30 logger.Println("This is a log message.")31 fmt.Println("This is a log message.")32}33import "log"34import "fmt"35import "os"36func main() {37 logger := log.New(os.Stdout, "FATAL: ", log.Ldate|log.Ltime|log.Lshortfile)38 logger.Println("This is a log message.")39 fmt.Println("This is a log message.")40}41import "log"42import "fmt"43import "os"44func main() {45 logger := log.New(os.Stdout, "PANIC: ", log.Ldate|log.Ltime|log.Lshortfile)46 logger.Println("This is a log message.")47 fmt.Println("This is a log message.")48}49import "log"50import "fmt"51import "os"
logInfo
Using AI Code Generation
1import (2func main() {3 logger := logrus.New()4 logger.SetFormatter(&logrus.JSONFormatter{})5 logger.Info("Info message")6}7import (8func main() {9 logger := logrus.New()10 logger.SetFormatter(&logrus.JSONFormatter{})11 logger.Info("Info message")12}13import (14func main() {15 logger := logrus.New()16 logger.SetFormatter(&logrus.JSONFormatter{})17 logger.SetReportCaller(true)18 logger.SetOutput(&lumberjack.Logger{19 })20 logger.Info("Info message")21}
logInfo
Using AI Code Generation
1import (2func main(){3 log.LogInfo("This is info")4}5import (6func main(){7 log.LogError("This is error")8}
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!!