123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308 |
- package klog
- import (
- "bufio"
- "bytes"
- "errors"
- "flag"
- "fmt"
- "io"
- stdLog "log"
- "math"
- "os"
- "path/filepath"
- "runtime"
- "strconv"
- "strings"
- "sync"
- "sync/atomic"
- "time"
- )
- type severity int32
- const (
- infoLog severity = iota
- warningLog
- errorLog
- fatalLog
- numSeverity = 4
- )
- const severityChar = "IWEF"
- var severityName = []string{
- infoLog: "INFO",
- warningLog: "WARNING",
- errorLog: "ERROR",
- fatalLog: "FATAL",
- }
- func (s *severity) get() severity {
- return severity(atomic.LoadInt32((*int32)(s)))
- }
- func (s *severity) set(val severity) {
- atomic.StoreInt32((*int32)(s), int32(val))
- }
- func (s *severity) String() string {
- return strconv.FormatInt(int64(*s), 10)
- }
- func (s *severity) Get() interface{} {
- return *s
- }
- func (s *severity) Set(value string) error {
- var threshold severity
-
- if v, ok := severityByName(value); ok {
- threshold = v
- } else {
- v, err := strconv.ParseInt(value, 10, 32)
- if err != nil {
- return err
- }
- threshold = severity(v)
- }
- logging.stderrThreshold.set(threshold)
- return nil
- }
- func severityByName(s string) (severity, bool) {
- s = strings.ToUpper(s)
- for i, name := range severityName {
- if name == s {
- return severity(i), true
- }
- }
- return 0, false
- }
- type OutputStats struct {
- lines int64
- bytes int64
- }
- func (s *OutputStats) Lines() int64 {
- return atomic.LoadInt64(&s.lines)
- }
- func (s *OutputStats) Bytes() int64 {
- return atomic.LoadInt64(&s.bytes)
- }
- var Stats struct {
- Info, Warning, Error OutputStats
- }
- var severityStats = [numSeverity]*OutputStats{
- infoLog: &Stats.Info,
- warningLog: &Stats.Warning,
- errorLog: &Stats.Error,
- }
- type Level int32
- func (l *Level) get() Level {
- return Level(atomic.LoadInt32((*int32)(l)))
- }
- func (l *Level) set(val Level) {
- atomic.StoreInt32((*int32)(l), int32(val))
- }
- func (l *Level) String() string {
- return strconv.FormatInt(int64(*l), 10)
- }
- func (l *Level) Get() interface{} {
- return *l
- }
- func (l *Level) Set(value string) error {
- v, err := strconv.ParseInt(value, 10, 32)
- if err != nil {
- return err
- }
- logging.mu.Lock()
- defer logging.mu.Unlock()
- logging.setVState(Level(v), logging.vmodule.filter, false)
- return nil
- }
- type moduleSpec struct {
- filter []modulePat
- }
- type modulePat struct {
- pattern string
- literal bool
- level Level
- }
- func (m *modulePat) match(file string) bool {
- if m.literal {
- return file == m.pattern
- }
- match, _ := filepath.Match(m.pattern, file)
- return match
- }
- func (m *moduleSpec) String() string {
-
- logging.mu.Lock()
- defer logging.mu.Unlock()
- var b bytes.Buffer
- for i, f := range m.filter {
- if i > 0 {
- b.WriteRune(',')
- }
- fmt.Fprintf(&b, "%s=%d", f.pattern, f.level)
- }
- return b.String()
- }
- func (m *moduleSpec) Get() interface{} {
- return nil
- }
- var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N")
- func (m *moduleSpec) Set(value string) error {
- var filter []modulePat
- for _, pat := range strings.Split(value, ",") {
- if len(pat) == 0 {
-
- continue
- }
- patLev := strings.Split(pat, "=")
- if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 {
- return errVmoduleSyntax
- }
- pattern := patLev[0]
- v, err := strconv.ParseInt(patLev[1], 10, 32)
- if err != nil {
- return errors.New("syntax error: expect comma-separated list of filename=N")
- }
- if v < 0 {
- return errors.New("negative value for vmodule level")
- }
- if v == 0 {
- continue
- }
-
- filter = append(filter, modulePat{pattern, isLiteral(pattern), Level(v)})
- }
- logging.mu.Lock()
- defer logging.mu.Unlock()
- logging.setVState(logging.verbosity, filter, true)
- return nil
- }
- func isLiteral(pattern string) bool {
- return !strings.ContainsAny(pattern, `\*?[]`)
- }
- type traceLocation struct {
- file string
- line int
- }
- func (t *traceLocation) isSet() bool {
- return t.line > 0
- }
- func (t *traceLocation) match(file string, line int) bool {
- if t.line != line {
- return false
- }
- if i := strings.LastIndex(file, "/"); i >= 0 {
- file = file[i+1:]
- }
- return t.file == file
- }
- func (t *traceLocation) String() string {
-
- logging.mu.Lock()
- defer logging.mu.Unlock()
- return fmt.Sprintf("%s:%d", t.file, t.line)
- }
- func (t *traceLocation) Get() interface{} {
- return nil
- }
- var errTraceSyntax = errors.New("syntax error: expect file.go:234")
- func (t *traceLocation) Set(value string) error {
- if value == "" {
-
- t.line = 0
- t.file = ""
- }
- fields := strings.Split(value, ":")
- if len(fields) != 2 {
- return errTraceSyntax
- }
- file, line := fields[0], fields[1]
- if !strings.Contains(file, ".") {
- return errTraceSyntax
- }
- v, err := strconv.Atoi(line)
- if err != nil {
- return errTraceSyntax
- }
- if v <= 0 {
- return errors.New("negative or zero value for level")
- }
- logging.mu.Lock()
- defer logging.mu.Unlock()
- t.line = v
- t.file = file
- return nil
- }
- type flushSyncWriter interface {
- Flush() error
- Sync() error
- io.Writer
- }
- func init() {
- logging.stderrThreshold = errorLog
- logging.setVState(0, nil, false)
- logging.logDir = ""
- logging.logFile = ""
- logging.logFileMaxSizeMB = 1800
- logging.toStderr = true
- logging.alsoToStderr = false
- logging.skipHeaders = false
- logging.addDirHeader = false
- logging.skipLogHeaders = false
- go logging.flushDaemon()
- }
- func InitFlags(flagset *flag.FlagSet) {
- if flagset == nil {
- flagset = flag.CommandLine
- }
- flagset.StringVar(&logging.logDir, "log_dir", logging.logDir, "If non-empty, write log files in this directory")
- flagset.StringVar(&logging.logFile, "log_file", logging.logFile, "If non-empty, use this log file")
- flagset.Uint64Var(&logging.logFileMaxSizeMB, "log_file_max_size", logging.logFileMaxSizeMB,
- "Defines the maximum size a log file can grow to. Unit is megabytes. "+
- "If the value is 0, the maximum file size is unlimited.")
- flagset.BoolVar(&logging.toStderr, "logtostderr", logging.toStderr, "log to standard error instead of files")
- flagset.BoolVar(&logging.alsoToStderr, "alsologtostderr", logging.alsoToStderr, "log to standard error as well as files")
- flagset.Var(&logging.verbosity, "v", "number for the log level verbosity")
- flagset.BoolVar(&logging.skipHeaders, "add_dir_header", logging.addDirHeader, "If true, adds the file directory to the header")
- flagset.BoolVar(&logging.skipHeaders, "skip_headers", logging.skipHeaders, "If true, avoid header prefixes in the log messages")
- flagset.BoolVar(&logging.skipLogHeaders, "skip_log_headers", logging.skipLogHeaders, "If true, avoid headers when opening log files")
- flagset.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr")
- flagset.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging")
- flagset.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace")
- }
- func Flush() {
- logging.lockAndFlushAll()
- }
- type loggingT struct {
-
-
-
- toStderr bool
- alsoToStderr bool
-
- stderrThreshold severity
-
- freeList *buffer
-
-
-
- freeListMu sync.Mutex
-
-
- mu sync.Mutex
-
- file [numSeverity]flushSyncWriter
-
- pcs [1]uintptr
-
-
- vmap map[uintptr]Level
-
-
-
- filterLength int32
-
- traceLocation traceLocation
-
-
- vmodule moduleSpec
- verbosity Level
-
-
- logDir string
-
-
- logFile string
-
-
- logFileMaxSizeMB uint64
-
- skipHeaders bool
-
- skipLogHeaders bool
-
- addDirHeader bool
- }
- type buffer struct {
- bytes.Buffer
- tmp [64]byte
- next *buffer
- }
- var logging loggingT
- func (l *loggingT) setVState(verbosity Level, filter []modulePat, setFilter bool) {
-
- logging.verbosity.set(0)
-
- atomic.StoreInt32(&logging.filterLength, 0)
-
- if setFilter {
- logging.vmodule.filter = filter
- logging.vmap = make(map[uintptr]Level)
- }
-
-
- atomic.StoreInt32(&logging.filterLength, int32(len(filter)))
- logging.verbosity.set(verbosity)
- }
- func (l *loggingT) getBuffer() *buffer {
- l.freeListMu.Lock()
- b := l.freeList
- if b != nil {
- l.freeList = b.next
- }
- l.freeListMu.Unlock()
- if b == nil {
- b = new(buffer)
- } else {
- b.next = nil
- b.Reset()
- }
- return b
- }
- func (l *loggingT) putBuffer(b *buffer) {
- if b.Len() >= 256 {
-
- return
- }
- l.freeListMu.Lock()
- b.next = l.freeList
- l.freeList = b
- l.freeListMu.Unlock()
- }
- var timeNow = time.Now
- 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
- }
- func (l *loggingT) formatHeader(s severity, file string, line int) *buffer {
- now := timeNow()
- if line < 0 {
- line = 0
- }
- if s > fatalLog {
- s = infoLog
- }
- buf := l.getBuffer()
- if l.skipHeaders {
- return buf
- }
-
-
- _, month, day := now.Date()
- hour, minute, second := now.Clock()
-
- 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, ' ')
- 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
- }
- const digits = "0123456789"
- func (buf *buffer) twoDigits(i, d int) {
- buf.tmp[i+1] = digits[d%10]
- d /= 10
- buf.tmp[i] = digits[d%10]
- }
- func (buf *buffer) nDigits(n, i, d int, pad byte) {
- j := n - 1
- for ; j >= 0 && d > 0; j-- {
- buf.tmp[i+j] = digits[d%10]
- d /= 10
- }
- for ; j >= 0; j-- {
- buf.tmp[i+j] = pad
- }
- }
- func (buf *buffer) someDigits(i, d int) int {
-
-
- j := len(buf.tmp)
- for {
- j--
- buf.tmp[j] = digits[d%10]
- d /= 10
- if d == 0 {
- break
- }
- }
- return copy(buf.tmp[i:], buf.tmp[j:])
- }
- func (l *loggingT) println(s severity, args ...interface{}) {
- buf, file, line := l.header(s, 0)
- fmt.Fprintln(buf, args...)
- l.output(s, buf, file, line, false)
- }
- func (l *loggingT) print(s severity, args ...interface{}) {
- l.printDepth(s, 1, args...)
- }
- func (l *loggingT) printDepth(s severity, depth int, args ...interface{}) {
- buf, file, line := l.header(s, depth)
- fmt.Fprint(buf, args...)
- if buf.Bytes()[buf.Len()-1] != '\n' {
- buf.WriteByte('\n')
- }
- l.output(s, buf, file, line, false)
- }
- func (l *loggingT) printf(s severity, format string, args ...interface{}) {
- buf, file, line := l.header(s, 0)
- fmt.Fprintf(buf, format, args...)
- if buf.Bytes()[buf.Len()-1] != '\n' {
- buf.WriteByte('\n')
- }
- l.output(s, buf, file, line, false)
- }
- func (l *loggingT) printWithFileLine(s severity, file string, line int, alsoToStderr bool, args ...interface{}) {
- buf := l.formatHeader(s, file, line)
- fmt.Fprint(buf, args...)
- if buf.Bytes()[buf.Len()-1] != '\n' {
- buf.WriteByte('\n')
- }
- l.output(s, buf, file, line, alsoToStderr)
- }
- type redirectBuffer struct {
- w io.Writer
- }
- func (rb *redirectBuffer) Sync() error {
- return nil
- }
- func (rb *redirectBuffer) Flush() error {
- return nil
- }
- func (rb *redirectBuffer) Write(bytes []byte) (n int, err error) {
- return rb.w.Write(bytes)
- }
- func SetOutput(w io.Writer) {
- logging.mu.Lock()
- defer logging.mu.Unlock()
- for s := fatalLog; s >= infoLog; s-- {
- rb := &redirectBuffer{
- w: w,
- }
- logging.file[s] = rb
- }
- }
- func SetOutputBySeverity(name string, w io.Writer) {
- logging.mu.Lock()
- defer logging.mu.Unlock()
- sev, ok := severityByName(name)
- if !ok {
- panic(fmt.Sprintf("SetOutputBySeverity(%q): unrecognized severity name", name))
- }
- rb := &redirectBuffer{
- w: w,
- }
- logging.file[sev] = rb
- }
- func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoToStderr bool) {
- l.mu.Lock()
- if l.traceLocation.isSet() {
- if l.traceLocation.match(file, line) {
- buf.Write(stacks(false))
- }
- }
- data := buf.Bytes()
- if l.toStderr {
- os.Stderr.Write(data)
- } else {
- if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() {
- os.Stderr.Write(data)
- }
- if logging.logFile != "" {
-
-
- if l.file[infoLog] == nil {
- if err := l.createFiles(infoLog); err != nil {
- os.Stderr.Write(data)
- l.exit(err)
- }
- }
- l.file[infoLog].Write(data)
- } else {
- if l.file[s] == nil {
- if err := l.createFiles(s); err != nil {
- os.Stderr.Write(data)
- l.exit(err)
- }
- }
- switch s {
- case fatalLog:
- l.file[fatalLog].Write(data)
- fallthrough
- case errorLog:
- l.file[errorLog].Write(data)
- fallthrough
- case warningLog:
- l.file[warningLog].Write(data)
- fallthrough
- case infoLog:
- l.file[infoLog].Write(data)
- }
- }
- }
- if s == fatalLog {
-
- if atomic.LoadUint32(&fatalNoStacks) > 0 {
- l.mu.Unlock()
- timeoutFlush(10 * time.Second)
- os.Exit(1)
- }
-
-
-
-
- if !l.toStderr {
- os.Stderr.Write(stacks(false))
- }
-
- trace := stacks(true)
- logExitFunc = func(error) {}
- for log := fatalLog; log >= infoLog; log-- {
- if f := l.file[log]; f != nil {
- f.Write(trace)
- }
- }
- l.mu.Unlock()
- timeoutFlush(10 * time.Second)
- os.Exit(255)
- }
- l.putBuffer(buf)
- l.mu.Unlock()
- if stats := severityStats[s]; stats != nil {
- atomic.AddInt64(&stats.lines, 1)
- atomic.AddInt64(&stats.bytes, int64(len(data)))
- }
- }
- func timeoutFlush(timeout time.Duration) {
- done := make(chan bool, 1)
- go func() {
- Flush()
- done <- true
- }()
- select {
- case <-done:
- case <-time.After(timeout):
- fmt.Fprintln(os.Stderr, "klog: Flush took longer than", timeout)
- }
- }
- func stacks(all bool) []byte {
-
- n := 10000
- if all {
- n = 100000
- }
- var trace []byte
- for i := 0; i < 5; i++ {
- trace = make([]byte, n)
- nbytes := runtime.Stack(trace, all)
- if nbytes < len(trace) {
- return trace[:nbytes]
- }
- n *= 2
- }
- return trace
- }
- var logExitFunc func(error)
- func (l *loggingT) exit(err error) {
- fmt.Fprintf(os.Stderr, "log: exiting because of error: %s\n", err)
-
- if logExitFunc != nil {
- logExitFunc(err)
- return
- }
- l.flushAll()
- os.Exit(2)
- }
- type syncBuffer struct {
- logger *loggingT
- *bufio.Writer
- file *os.File
- sev severity
- nbytes uint64
- maxbytes uint64
- }
- func (sb *syncBuffer) Sync() error {
- return sb.file.Sync()
- }
- func CalculateMaxSize() uint64 {
- if logging.logFile != "" {
- if logging.logFileMaxSizeMB == 0 {
-
- return math.MaxUint64
- }
-
- return logging.logFileMaxSizeMB * 1024 * 1024
- }
-
- return MaxSize
- }
- func (sb *syncBuffer) Write(p []byte) (n int, err error) {
- if sb.nbytes+uint64(len(p)) >= sb.maxbytes {
- if err := sb.rotateFile(time.Now(), false); err != nil {
- sb.logger.exit(err)
- }
- }
- n, err = sb.Writer.Write(p)
- sb.nbytes += uint64(n)
- if err != nil {
- sb.logger.exit(err)
- }
- return
- }
- func (sb *syncBuffer) rotateFile(now time.Time, startup bool) error {
- if sb.file != nil {
- sb.Flush()
- sb.file.Close()
- }
- var err error
- sb.file, _, err = create(severityName[sb.sev], now, startup)
- sb.nbytes = 0
- if err != nil {
- return err
- }
- sb.Writer = bufio.NewWriterSize(sb.file, bufferSize)
- if sb.logger.skipLogHeaders {
- return nil
- }
-
- var buf bytes.Buffer
- fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05"))
- fmt.Fprintf(&buf, "Running on machine: %s\n", host)
- fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH)
- fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg\n")
- n, err := sb.file.Write(buf.Bytes())
- sb.nbytes += uint64(n)
- return err
- }
- const bufferSize = 256 * 1024
- func (l *loggingT) createFiles(sev severity) error {
- now := time.Now()
-
-
- for s := sev; s >= infoLog && l.file[s] == nil; s-- {
- sb := &syncBuffer{
- logger: l,
- sev: s,
- maxbytes: CalculateMaxSize(),
- }
- if err := sb.rotateFile(now, true); err != nil {
- return err
- }
- l.file[s] = sb
- }
- return nil
- }
- const flushInterval = 5 * time.Second
- func (l *loggingT) flushDaemon() {
- for range time.NewTicker(flushInterval).C {
- l.lockAndFlushAll()
- }
- }
- func (l *loggingT) lockAndFlushAll() {
- l.mu.Lock()
- l.flushAll()
- l.mu.Unlock()
- }
- func (l *loggingT) flushAll() {
-
- for s := fatalLog; s >= infoLog; s-- {
- file := l.file[s]
- if file != nil {
- file.Flush()
- file.Sync()
- }
- }
- }
- func CopyStandardLogTo(name string) {
- sev, ok := severityByName(name)
- if !ok {
- panic(fmt.Sprintf("log.CopyStandardLogTo(%q): unrecognized severity name", name))
- }
-
-
- stdLog.SetFlags(stdLog.Lshortfile)
- stdLog.SetOutput(logBridge(sev))
- }
- type logBridge severity
- func (lb logBridge) Write(b []byte) (n int, err error) {
- var (
- file = "???"
- line = 1
- text string
- )
-
- if parts := bytes.SplitN(b, []byte{':'}, 3); len(parts) != 3 || len(parts[0]) < 1 || len(parts[2]) < 1 {
- text = fmt.Sprintf("bad log format: %s", b)
- } else {
- file = string(parts[0])
- text = string(parts[2][1:])
- line, err = strconv.Atoi(string(parts[1]))
- if err != nil {
- text = fmt.Sprintf("bad line number: %s", b)
- line = 1
- }
- }
-
-
- logging.printWithFileLine(severity(lb), file, line, true, text)
- return len(b), nil
- }
- func (l *loggingT) setV(pc uintptr) Level {
- fn := runtime.FuncForPC(pc)
- file, _ := fn.FileLine(pc)
-
- if strings.HasSuffix(file, ".go") {
- file = file[:len(file)-3]
- }
- if slash := strings.LastIndex(file, "/"); slash >= 0 {
- file = file[slash+1:]
- }
- for _, filter := range l.vmodule.filter {
- if filter.match(file) {
- l.vmap[pc] = filter.level
- return filter.level
- }
- }
- l.vmap[pc] = 0
- return 0
- }
- type Verbose bool
- func V(level Level) Verbose {
-
-
-
- if logging.verbosity.get() >= level {
- return Verbose(true)
- }
-
-
- if atomic.LoadInt32(&logging.filterLength) > 0 {
-
-
-
- logging.mu.Lock()
- defer logging.mu.Unlock()
- if runtime.Callers(2, logging.pcs[:]) == 0 {
- return Verbose(false)
- }
- v, ok := logging.vmap[logging.pcs[0]]
- if !ok {
- v = logging.setV(logging.pcs[0])
- }
- return Verbose(v >= level)
- }
- return Verbose(false)
- }
- func (v Verbose) Info(args ...interface{}) {
- if v {
- logging.print(infoLog, args...)
- }
- }
- func (v Verbose) Infoln(args ...interface{}) {
- if v {
- logging.println(infoLog, args...)
- }
- }
- func (v Verbose) Infof(format string, args ...interface{}) {
- if v {
- logging.printf(infoLog, format, args...)
- }
- }
- func Info(args ...interface{}) {
- logging.print(infoLog, args...)
- }
- func InfoDepth(depth int, args ...interface{}) {
- logging.printDepth(infoLog, depth, args...)
- }
- func Infoln(args ...interface{}) {
- logging.println(infoLog, args...)
- }
- func Infof(format string, args ...interface{}) {
- logging.printf(infoLog, format, args...)
- }
- func Warning(args ...interface{}) {
- logging.print(warningLog, args...)
- }
- func WarningDepth(depth int, args ...interface{}) {
- logging.printDepth(warningLog, depth, args...)
- }
- func Warningln(args ...interface{}) {
- logging.println(warningLog, args...)
- }
- func Warningf(format string, args ...interface{}) {
- logging.printf(warningLog, format, args...)
- }
- func Error(args ...interface{}) {
- logging.print(errorLog, args...)
- }
- func ErrorDepth(depth int, args ...interface{}) {
- logging.printDepth(errorLog, depth, args...)
- }
- func Errorln(args ...interface{}) {
- logging.println(errorLog, args...)
- }
- func Errorf(format string, args ...interface{}) {
- logging.printf(errorLog, format, args...)
- }
- func Fatal(args ...interface{}) {
- logging.print(fatalLog, args...)
- }
- func FatalDepth(depth int, args ...interface{}) {
- logging.printDepth(fatalLog, depth, args...)
- }
- func Fatalln(args ...interface{}) {
- logging.println(fatalLog, args...)
- }
- func Fatalf(format string, args ...interface{}) {
- logging.printf(fatalLog, format, args...)
- }
- var fatalNoStacks uint32
- func Exit(args ...interface{}) {
- atomic.StoreUint32(&fatalNoStacks, 1)
- logging.print(fatalLog, args...)
- }
- func ExitDepth(depth int, args ...interface{}) {
- atomic.StoreUint32(&fatalNoStacks, 1)
- logging.printDepth(fatalLog, depth, args...)
- }
- func Exitln(args ...interface{}) {
- atomic.StoreUint32(&fatalNoStacks, 1)
- logging.println(fatalLog, args...)
- }
- func Exitf(format string, args ...interface{}) {
- atomic.StoreUint32(&fatalNoStacks, 1)
- logging.printf(fatalLog, format, args...)
- }
|