douang1243 2016-10-30 20:31
浏览 46
已采纳

在Golang中实现最小的记录器

I've created a minimal logger in Golang. I tried to keep it as simple as possible but two problems arise:

  • Message string is shown as array wrapped in brackets []
  • filename using log.Lshortfile flag is always shown as logger.go

CMD

Here's my code:

package logger

import (
    "log"
    "os"
)

var (
    dlog = log.New(os.Stdout, "\x1B[36mDEBUG: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
    wlog = log.New(os.Stdout, "\x1B[35mWARN: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
    ilog = log.New(os.Stdout, "\x1B[32mINFO: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
    elog = log.New(os.Stderr, "\x1B[31mERROR: \x1B[0m", log.Ldate|log.Ltime|log.Lshortfile)
)

// Debug Log
func Debug(a ...interface{}) {
     dlog.Println(a)
}

// Warn log
func Warn(a ...interface{}) {
    wlog.Println(a)
}

// Info Log
func Info(a ...interface{}) {
    ilog.Println(a)
}

// Error Log
func Error(a ...interface{}) {
    elog.Println(a)
}

I use them like this: logger.Debug("Hello") or logger.Info("There")

How do I implement this correctly? Thank you.

  • 写回答

1条回答 默认 最新

  • dpztth71739 2016-10-30 20:37
    关注

    Println is passed a single parameter, a slice of interface{}, and prints it using slice notation. To fix this, pass the variadic parameters to your functions as variadic arguments to the called functions.

    func Debug(a ...interface{}) {
         dlog.Println(a...) // <-- note ... here
    }
    

    Here's the doc on variadic args.

    Call Output to workaround the file name issue.

    func Debug(a ...interface{}) {
         dlog.Output(2, fmt.Sprintln(a...))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用