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...))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行