drbe16008 2019-05-11 22:51
浏览 44
已采纳

替换* os.Go默认日志文件

I'm trying to write a wrapper for Go's built-in logger. This is to have compatibility.

package main

import (
    "log"
    "os"
)

var(
    mylog *log.Logger
)

func main() {
    mylog = log.New(os.Stdout, "", 0)
    mylog.Printf("test")
}

Instead of using os.Stdout, I want to create one something. Similar to os.Stdout but prints with prefix like below.

package main

import( 
    "log"
    "mylibrary"
)

var(
    mylog *log.Logger
)

func main() {
    mylog = log.New(mylibrary.Prefix, "", 0)
    mylog.Printf("test")
}

Basically, I still want to have *log.Logger while having custom log. Can someone give me a hint how I can make this works?

Currently, I'm using following to do that. But I bet there's a better way.

func NewIoWriter(f func(string)) *io.PipeWriter {
    r, w := io.Pipe()
    go func() {
        scanner := bufio.NewScanner(r)
        for scanner.Scan() {
            f(scanner.Text())
        }
        if err := scanner.Err(); err != nil {
            f(err.Error())
        }
        r.Close()
    }()
    runtime.SetFinalizer(w, (*io.PipeWriter).Close)
    return w
}

What would be the better way to make it work?

Thank you

  • 写回答

1条回答 默认 最新

  • dongying6896 2019-05-12 00:23
    关注

    How about something like this:

    type myLogWriter struct {
        logFunc func(string)
        line    string
    }
    
    func (w *myLogWriter) Write(b []byte) (int, error) {
        l := len(b)
        for len(b) != 0 {
            i := bytes.Index(b, []byte{'
    '})
            if i == -1 {
                w.line += string(b)
                break
            } else {
                w.logFunc(w.line + string(b[:i]))
                b = b[i+1:]
                w.line = ""
            }
        }
    
        return l, nil
    }
    
    func NewLogWriter(f func(string)) *myLogWriter {
        return &myLogWriter{
            logFunc: f,
        }
    }
    

    See https://play.golang.org/p/L6PG1gCK1er.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库