Golang log库 源码阅读

栏目: Go · 发布时间: 7年前

内容简介:Golang的log库。。。还是太简单,简单瞄了一下实现,差不多就是这样:测试用例:运行结果:

Golang的log库。。。还是太简单,简单瞄了一下实现,差不多就是这样:

package main

import (
    "fmt"
    "io"
    "os"
    "sync"
)

type Logger struct {
    mu  sync.Mutex
    out io.Writer
}

func New(out io.Writer) *Logger {
    return &Logger{out: out}
}

func (l *Logger) output(format string, v ...interface{}) {
    l.mu.Lock()
    defer l.mu.Unlock()

    l.out.Write([]byte(fmt.Sprintf(format, v...)))
}

func (l *Logger) Printf(format string, v ...interface{}) {
    l.output(format, v...)
}

func (l *Logger) Panicf(format string, v ...interface{}) {
    l.output(format, v...)
    panic("traceback:\n")
}

func (l *Logger) Fatalf(format string, v ...interface{}) {
    l.output(format, v...)
    os.Exit(1)
}

var std = New(os.Stderr)

func Printf(format string, v ...interface{}) {
    std.Printf(format, v...)
}

func Panicf(format string, v ...interface{}) {
    std.Panicf(format, v...)
}

func Fatalf(format string, v ...interface{}) {
    std.Fatalf(format, v...)
}

测试用例:

package main

func main() {
    std.Printf("this is: %d\n", 1)

    std.Panicf("bye\n")
}

运行结果:

root@arch test: ./main          
this is: 1                      
bye                             
panic: traceback:               


goroutine 1 [running]:          
main.(*Logger).Panicf(0xc42006a060, 0x4a7115, 0x4, 0x0, 0x0, 0x0)                                                                
        /root/test/mylog.go:32 +0xa8                            
main.main()                     
        /root/test/main.go:6 +0xeb                              
root@arch test:

以上所述就是小编给大家介绍的《Golang log库 源码阅读》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Python高效开发实战

Python高效开发实战

刘长龙 / 电子工业出版社 / 2016-10 / 89

也许你听说过全栈工程师,他们善于设计系统架构,精通数据库建模、通用网络协议、后端并发处理、前端界面设计,在学术研究或工程项目上能独当一面。通过对Python及其周边Web框架的学习和实践,你就可以成为这样的全能型人才。 《Python高效开发实战——Django、Tornado、Flask、Twisted》分为3部分:第1部分是基础篇,带领初学者实践Python开发环境和掌握基本语法,同时对......一起来看看 《Python高效开发实战》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具