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?

图片转代码服务由CSDN问答提供 功能建议

  func(log Logger)警告(arg0接口{},args ...接口{})错误 {
const(
 lvl =警告
)
var msg字符串
首先切换:= arg0。(类型){
case字符串:
 //使用字符串作为格式字符串
 msg = fmt.Sprintf( 首先,args ...)
case func()字符串:
 //记录闭包(不使用其他任何参数)
 msg = first()
default:
 //构建格式字符串,以便将 类似于Sprint 
 msg = fmt.Sprintf(fmt.Sprint(first)+ strings.Repeat(“%v”,len(args)),args ...)
} 
log.intLogf(lvl,msg)  
返回错误。New(msg)
} 
 
func(日志记录器)Info(arg0接口{},args ...接口{}){
const(
 lvl = INFO 
)
先切换:  = arg0。(type){
case string:
 //使用字符串作为格式字符串
 log.intLogf(lvl,first,args ...)
case func()string:
 //记录 闭包(不使用其他任何参数)
 log.intLogc(lvl,第一个)
默认值:
 //构建格式字符串,使其类似于Sprin  t 
 log.intLogf(lvl,fmt.Sprint(arg0)+ strings.Repeat(“%v”,len(args)),args ...)
} 
   \  n 
 

}

这两个函数来自log4go库的源代码,我不知道为什么Warn(实际上所有级别都比Warn高)与Info不同,为什么 Info会将所有args传递给iniLogf函数以处理日志记录时,首先警告功能Sprintf味精吗? 是因为如果在那个时候流程中止,关闭可能会遗漏?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题