Skip to content

Commit 2088315

Browse files
zhiweivtamilmani1989
authored andcommitted
Add pid to log (#360)
* add pid to log * fix code format
1 parent c7c3dd9 commit 2088315

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

log/logger.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ type Logger struct {
5757
mutex *sync.Mutex
5858
}
5959

60+
var pid = os.Getpid()
61+
6062
// NewLogger creates a new Logger.
6163
func NewLogger(name string, level int, target int) *Logger {
6264
var logger Logger
@@ -190,7 +192,7 @@ func (logger *Logger) logf(format string, args ...interface{}) {
190192
if logger.callCount%rotationCheckFrq == 0 {
191193
logger.rotate()
192194
}
193-
195+
format = fmt.Sprintf("[%v] %s", pid, format)
194196
logger.callCount++
195197
logger.l.Printf(format, args...)
196198
}

log/logger_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44
package log
55

66
import (
7+
"fmt"
8+
"io/ioutil"
79
"os"
10+
"strings"
811
"testing"
912
)
1013

@@ -48,3 +51,26 @@ func TestLogFileRotatesWhenSizeLimitIsReached(t *testing.T) {
4851
}
4952
os.Remove(fn)
5053
}
54+
55+
func TestPid(t *testing.T) {
56+
l := NewLogger(logName, LevelInfo, TargetLogfile)
57+
if l == nil {
58+
t.Fatalf("Failed to create logger.")
59+
}
60+
61+
l.Printf("LogText %v", 1)
62+
l.Close()
63+
fn := l.GetLogDirectory() + logName + ".log"
64+
defer os.Remove(fn)
65+
66+
logBytes, err := ioutil.ReadFile(fn)
67+
if err != nil {
68+
t.Fatalf("Failed to read log, %v", err)
69+
}
70+
log := string(logBytes)
71+
exptectedLog := fmt.Sprintf("[%v] LogText 1", os.Getpid());
72+
73+
if !strings.Contains(log, exptectedLog){
74+
t.Fatalf("Unexpected log: %s.", log)
75+
}
76+
}

0 commit comments

Comments
 (0)