dongquming3255 2018-02-21 16:46
浏览 36
已采纳

Golang-创建自定义记录器以在整个应用程序中共享文件和软件包

In my program there is a lot places where I should create logs like following

log.Println("[Build]: bla bla“)

log.Println(“[INFO]: bla bla“)

log.Printf(“[ERROR]: bla bla“)

log.Println(“[WARNING]: bla bla“)

I use it for all my logging in different packages inside the application and it’s bit frustrating to copy this, is there a way to create some generic log which I can simple re-use it inside my program.

I read about logrus etc but they provide some way to do it but not provide some custom way or maybe I miss something.

My program is command line tool

  • 写回答

1条回答 默认 最新

  • dskld5423 2018-02-21 17:33
    关注

    It's best to use a more proper logger like zap or logrus. Also prefer passing the logger explicitly as an argument and avoid global loggers.

    Yet if the exact logging workflow with the built-in one is needed, with the provided sample output, it's possible to define them with proper prefixes, instead of repeating the level in each string:

    var (
        warnlog  = log.New(os.Stderr, "[ warn  ]", log.Ltime|log.Lshortfile)
        infolog  = log.New(os.Stderr, "[ info  ]", log.Ltime|log.Lshortfile)
        buildlog = log.New(os.Stderr, "[ build ]", log.Ltime|log.Lshortfile)
        errlog   = log.New(os.Stderr, "[ error ]", log.Ltime|log.Lshortfile)
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入