doushupu2521 2018-01-09 03:26
浏览 26
已采纳

为什么这些具有相同功能的方法写的不同?

func (log Logger) Warn(arg0 interface{}, args ...interface{}) error {
const (
    lvl = WARNING
)
var msg string
switch first := arg0.(type) {
case string:
    // Use the string as a format string
    msg = fmt.Sprintf(first, args...)
case func() string:
    // Log the closure (no other arguments used)
    msg = first()
default:
    // Build a format string so that it will be similar to Sprint
    msg = fmt.Sprintf(fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...)
}
log.intLogf(lvl, msg)
return errors.New(msg)
}

func (log Logger) Info(arg0 interface{}, args ...interface{}) {
const (
    lvl = INFO
)
switch first := arg0.(type) {
case string:
    // Use the string as a format string
    log.intLogf(lvl, first, args...)
case func() string:
    // Log the closure (no other arguments used)
    log.intLogc(lvl, first)
default:
    // Build a format string so that it will be similar to Sprint
    log.intLogf(lvl, fmt.Sprint(arg0)+strings.Repeat(" %v", len(args)), args...)
}

}

These two functions are from log4go library's source code,I don't know why Warn(in fact all level higher than Warn) is different from Info, Why does Warn function Sprintf the msg first while Info passes all args to the iniLogf function to handle the logging? Is it because the closure may be leave out if the process aborted at that timing?

  • 写回答

1条回答 默认 最新

  • douji1077 2018-01-09 03:41
    关注

    The most likely explanation is that due to the fact that Logger.Warn method returns an error value, it was refactored to at first save the value it needs to log into variable msg and then log it separately as well as return it as the error. Logger.Info, at the same time, logs the message as soon as it is possible because it is not required to return the message. This seems to be the only difference in the way these functions work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝