Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix #1272 #1273

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions exported.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,3 +268,15 @@ func Panicln(args ...interface{}) {
func Fatalln(args ...interface{}) {
std.Fatalln(args...)
}

func Lock() {
if !std.mu.disabled {
std.mu.Lock()
}
}

func Unlock() {
if !std.mu.disabled {
std.mu.Unlock()
}
}
128 changes: 127 additions & 1 deletion logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,15 @@ package logrus

import (
"bytes"
"context"
"encoding/json"
"fmt"
"path/filepath"
"runtime"
"strconv"
"sync"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -70,7 +76,7 @@ func TestWarninglnNotEqualToWarning(t *testing.T) {

type testBufferPool struct {
buffers []*bytes.Buffer
get int
get int
}

func (p *testBufferPool) Get() *bytes.Buffer {
Expand All @@ -95,3 +101,123 @@ func TestLogger_SetBufferPool(t *testing.T) {
assert.Equal(t, pool.get, 1, "Logger.SetBufferPool(): The BufferPool.Get() must be called")
assert.Len(t, pool.buffers, 1, "Logger.SetBufferPool(): The BufferPool.Put() must be called")
}

func TestLogger_concurrentLock(t *testing.T) {
SetFormatter(&LogFormatter{})
go func() {
for {
func() {
defer func() {
// 处理所有异常,防止panic导致程序关闭
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does this comment says?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sry I have deleted unnecessary Chinese comments

if p := recover(); p != nil {
}
}()
hook := AddTraceIdHook("123")
defer RemoveTraceHook(hook)
Infof("test why ")
}()
}
}()
go func() {
for {
func() {
defer func() {
// 处理所有异常,防止panic导致程序关闭
if p := recover(); p != nil {
}
}()
hook := AddTraceIdHook("1233")
defer RemoveTraceHook(hook)
Infof("test why 2")
}()
}
}()
time.Sleep(1 * time.Minute)
}

var traceLock = &sync.Mutex{}

func AddTraceIdHook(traceId string) Hook {
defer traceLock.Unlock()
traceLock.Lock()
traceHook := newTraceIdHook(traceId)
if StandardLogger().Hooks == nil {
hooks := new(LevelHooks)
StandardLogger().ReplaceHooks(*hooks)
}
AddHook(traceHook)
return traceHook
}

func RemoveTraceHook(hook Hook) {
allHooks := StandardLogger().Hooks
func() {
defer Unlock()
Lock()
for key, hooks := range allHooks {
replaceHooks := hooks
for index, h := range hooks {
if h == hook {
replaceHooks = append(hooks[:index], hooks[index:]...)
break
}
}
allHooks[key] = replaceHooks
}
}()

StandardLogger().ReplaceHooks(allHooks)
}

type TraceIdHook struct {
TraceId string
GID uint64
}

func newTraceIdHook(traceId string) Hook {
return &TraceIdHook{
TraceId: traceId,
GID: getGID(),
}
}

func (t TraceIdHook) Levels() []Level {
return AllLevels
}

func (t TraceIdHook) Fire(entry *Entry) error {
if getGID() == t.GID {
entry.Context = context.WithValue(context.Background(), "trace_id", t.TraceId)
}
return nil
}

type LogFormatter struct{}

//格式详情
func (s *LogFormatter) Format(entry *Entry) ([]byte, error) {
timestamp := time.Now().Format("2006-01-02 15:04:05")
var file string
var line int
if entry.Caller != nil {
file = filepath.Base(entry.Caller.File)
line = entry.Caller.Line
}
level := entry.Level.String()
if entry.Context == nil || entry.Context.Value("trace_id") == "" {
uuid := "NO UUID"
entry.Context = context.WithValue(context.Background(), "trace_id", uuid)
}
msg := fmt.Sprintf("%-15s [%-3d] [%-5s] [%s] %s:%d %s\n", timestamp, getGID(), level, entry.Context.Value("trace_id"), file, line, entry.Message)
return []byte(msg), nil
}

// 获取当前协程id
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and this?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have deleted unnecessary Chinese comments

func getGID() uint64 {
b := make([]byte, 64)
b = b[:runtime.Stack(b, false)]
b = bytes.TrimPrefix(b, []byte("goroutine "))
b = b[:bytes.IndexByte(b, ' ')]
n, _ := strconv.ParseUint(string(b), 10, 64)
return n
}