聊聊klog的header

算法聆星人
• 阅读 2641

本文主要研究一下klog的header

println

k8s.io/klog/v2@v2.4.0/klog.go

func (l *loggingT) println(s severity, logr logr.Logger, filter LogFilter, args ...interface{}) {
    buf, file, line := l.header(s, 0)
    // if logr is set, we clear the generated header as we rely on the backing
    // logr implementation to print headers
    if logr != nil {
        l.putBuffer(buf)
        buf = l.getBuffer()
    }
    if filter != nil {
        args = filter.Filter(args)
    }
    fmt.Fprintln(buf, args...)
    l.output(s, logr, buf, file, line, false)
}
println方法先执行l.header(s, 0),若logr不为nil则先l.putBuffer(buf),然后重新设置buf

header

k8s.io/klog/v2@v2.4.0/klog.go

func (l *loggingT) header(s severity, depth int) (*buffer, string, int) {
    _, file, line, ok := runtime.Caller(3 + depth)
    if !ok {
        file = "???"
        line = 1
    } else {
        if slash := strings.LastIndex(file, "/"); slash >= 0 {
            path := file
            file = path[slash+1:]
            if l.addDirHeader {
                if dirsep := strings.LastIndex(path[:slash], "/"); dirsep >= 0 {
                    file = path[dirsep+1:]
                }
            }
        }
    }
    return l.formatHeader(s, file, line), file, line
}
header方法最后执行l.formatHeader

formatHeader

k8s.io/klog/v2@v2.4.0/klog.go

// formatHeader formats a log header using the provided file name and line number.
func (l *loggingT) formatHeader(s severity, file string, line int) *buffer {
    now := timeNow()
    if line < 0 {
        line = 0 // not a real line number, but acceptable to someDigits
    }
    if s > fatalLog {
        s = infoLog // for safety.
    }
    buf := l.getBuffer()
    if l.skipHeaders {
        return buf
    }

    // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand.
    // It's worth about 3X. Fprintf is hard.
    _, month, day := now.Date()
    hour, minute, second := now.Clock()
    // Lmmdd hh:mm:ss.uuuuuu threadid file:line]
    buf.tmp[0] = severityChar[s]
    buf.twoDigits(1, int(month))
    buf.twoDigits(3, day)
    buf.tmp[5] = ' '
    buf.twoDigits(6, hour)
    buf.tmp[8] = ':'
    buf.twoDigits(9, minute)
    buf.tmp[11] = ':'
    buf.twoDigits(12, second)
    buf.tmp[14] = '.'
    buf.nDigits(6, 15, now.Nanosecond()/1000, '0')
    buf.tmp[21] = ' '
    buf.nDigits(7, 22, pid, ' ') // TODO: should be TID
    buf.tmp[29] = ' '
    buf.Write(buf.tmp[:30])
    buf.WriteString(file)
    buf.tmp[0] = ':'
    n := buf.someDigits(1, line)
    buf.tmp[n+1] = ']'
    buf.tmp[n+2] = ' '
    buf.Write(buf.tmp[:n+3])
    return buf
}
如果设置了l.skipHeaders,则不会进行format

实例

func headerDemo() {
    flag.Set("skip_headers", "true")
    klog.Info("hello by Info")
    klog.InfoDepth(0, "hello by InfoDepth 0")
    klog.InfoDepth(1, "hello by InfoDepth 1")
    klog.Infoln("hello by Infoln")
    klog.Infof("hello by %s", "Infof")
    klog.InfoS("Pod status updated", "pod", "kubedns", "status", "ready")
}

输出

hello by Info
hello by InfoDepth 0
hello by InfoDepth 1
hello by Infoln
hello by Infof
"Pod status updated" pod="kubedns" status="ready"

默认带header输出如下

I1229 23:45:57.827487    2176 klog_demo.go:41] hello by Info
I1229 23:45:57.827591    2176 klog_demo.go:42] hello by InfoDepth 0
I1229 23:45:57.827600    2176 klog_demo.go:31] hello by InfoDepth 1
I1229 23:45:57.827605    2176 klog_demo.go:44] hello by Infoln
I1229 23:45:57.827608    2176 klog_demo.go:45] hello by Infof
I1229 23:45:57.827617    2176 klog_demo.go:46] "Pod status updated" pod="kubedns" status="ready"

小结

如果设置klog的skip_headers为true,则其l.skipHeaders为true,则不会格式化并输出header信息。

doc

点赞
收藏
评论区
推荐文章
blmius blmius
4年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Wesley13 Wesley13
4年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
科工人 科工人
4年前
聊聊golang的DDD项目结构
序本文主要研究一下golang的DDD项目结构interfacesfoodappserver/interfacesinterfacesgit:(master)tree.|____fileupload||____fileformat.go||____fileupload.go|____food_handler.go|__
Wesley13 Wesley13
4年前
jmxtrans+influxdb+grafana监控zookeeper实战
序本文主要研究一下如何使用jmxtransinfluxdbgranfa监控zookeeper配置zookeeperjmx在conf目录下新增zookeeperenv.sh,并使用chmodx赋予执行权限,内容如下JMXLOCALONLYfalseJMXDISABLEfals
Stella981 Stella981
4年前
Python+Selenium自动化篇
本篇文字主要学习selenium定位页面元素的集中方法,以百度首页为例子。0.元素定位方法主要有:id定位:find\_element\_by\_id('')name定位:find\_element\_by\_name('')class定位:find\_element\_by\_class\_name(''
Wesley13 Wesley13
4年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Wesley13 Wesley13
4年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
4年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Stella981 Stella981
4年前
RedisTemplate读取slowlog
序本文主要研究一下如何使用RedisTemplate(lettuce类库)读取slowlogmaven<dependency<groupIdorg.springframework.boot</groupId<artifactIdspringbootstarterdata
Stella981 Stella981
4年前
Linux日志安全分析技巧
0x00前言我正在整理一个项目,收集和汇总了一些应急响应案例(不断更新中)。GitHub地址:https://github.com/Bypass007/EmergencyResponseNotes本文主要介绍Linux日志分析的技巧,更多详细信息请访问Github地址,欢迎Star。0x01日志简介Lin