dsgffz2579 2017-05-18 14:40
浏览 75
已采纳

使用多个后端进行日志记录

I'm using go-logging and I'm trying to build a logger with a variable number of Backends (i.e. stderr + file + syslog + ...). So my program reads a configuration file, and create the logger according to what's defined.

As SetBackend is a variadic function, I thought I could use a slice as argument, but I was wrong.

Here is an example of my code:

func configureLogger(debug, file bool) {
    var backendList = []logging.Backend{}
    var format = logging.MustStringFormatter(
        `%{color}%{time:15:04:05.000} [%{level:.4s}] %{shortfunc}%{color:reset}: %{message}`,
    )

    if debug {
        consoleBackend := logging.NewLogBackend(os.Stderr, "", 0)
        consoleBackendFormatter := logging.NewBackendFormatter(consoleBackend, format)
        consoleBackendLeveled := logging.AddModuleLevel(consoleBackendFormatter)
        consoleBackendLeveled.SetLevel(logging.DEBUG, "")
        backendList = append(backendList, consoleBackendLeveled)
    }

    if file {
        f, err := os.OpenFile("file.log", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0644)
        filebackend := logging.NewLogBackend(f, "", 0)
        filebackendFormatter := logging.NewBackendFormatter(filebackend, format)
        filebackendLeveled := logging.AddModuleLevel(filebackendFormatter)
        filebackendLeveled.SetLevel(logging.DEBUG, "")
        backendList = append(backendList, filebackendLeveled)
    }

    logging.SetBackend(backendList)
}

This end up with the following error:

cannot use backendList (type []logging.Backend) as type logging.Backend in argument to logging.SetBackend:
    []logging.Backend does not implement logging.Backend (missing Log method)

What am I missing?

  • 写回答

1条回答 默认 最新

  • doufang3001 2017-05-18 14:58
    关注

    I was missing the good syntax. When passing a slice to a variadic function, you need to add ... after your slice name, as shown in the specs: https://golang.org/ref/spec#Passing_arguments_to_..._parameters

    The right syntax is:

    logging.SetBackend(backendList...)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度