@@ -2,6 +2,7 @@ package zapx
22
33import (
44 "path"
5+ "slices"
56 "sort"
67
78 "go.uber.org/zap"
@@ -15,49 +16,53 @@ type SlowlogEncoder struct {
1516}
1617
1718func NewSlowlogEncoder () * SlowlogEncoder {
18- return & SlowlogEncoder {strBuf : make ([]string , 0 )}
19+ return & SlowlogEncoder {strBuf : make ([]string , 0 , 32 )}
1920}
2021
2122func (sle * SlowlogEncoder ) reset () {
2223 sle .strBuf = sle .strBuf [:0 ]
2324}
2425
2526func (sle * SlowlogEncoder ) add (s string ) {
26- if l := len (sle .strBuf ); l > 1 && sle .strBuf [l - 1 ] == s {
27+ i := sort .SearchStrings (sle .strBuf , s )
28+ if i < len (sle .strBuf ) && sle .strBuf [i ] == s {
29+ // Do not insert duplicates
2730 return
2831 }
2932
30- i := sort .SearchStrings (sle .strBuf , s )
31- sle .strBuf = append (sle .strBuf , "" )
32- copy (sle .strBuf [i + 1 :], sle .strBuf [i :])
33-
34- sle .strBuf [i ] = s
33+ sle .strBuf = slices .Insert (sle .strBuf , i , s )
3534}
3635
37- func (sle * SlowlogEncoder ) addDir (p string ) {
38- sle .add (path .Dir (p ))
36+ func (sle * SlowlogEncoder ) addDir (p string ) bool {
37+ dir , _ := path .Split (p )
38+ if dir == "" {
39+ return false
40+ }
41+
42+ sle .add (path .Clean (dir ))
43+
44+ return true
3945}
4046
4147func (sle * SlowlogEncoder ) longestCommonPrefOffset () int {
42- offset := 0
43- endPrefix := false
44-
4548 if len (sle .strBuf ) <= 0 {
4649 return 0
4750 }
4851
52+ if len (sle .strBuf ) == 1 {
53+ return len (sle .strBuf [0 ]) + 1
54+ }
55+
4956 first := sle .strBuf [0 ]
5057 last := sle .strBuf [len (sle .strBuf )- 1 ]
5158
5259 for i := 0 ; i < len (first ); i ++ {
53- if ! endPrefix && last [i ] == first [i ] {
54- offset = i + 1
55- } else {
56- endPrefix = true
60+ if last [i ] != first [i ] {
61+ return i
5762 }
5863 }
5964
60- return offset
65+ return 0
6166}
6267
6368func (sle * SlowlogEncoder ) encodeStacktraceEntry (encoder zapcore.ObjectEncoder , entry phpfpm.SlowlogTraceEntry , pathOffset int ) {
@@ -89,12 +94,15 @@ func (sle *SlowlogEncoder) encodeStacktrace(stacktrace []phpfpm.SlowlogTraceEntr
8994func (sle * SlowlogEncoder ) Encode (entry phpfpm.SlowlogEntry ) []zap.Field {
9095 sle .reset ()
9196
92- sle .addDir (entry .ScriptFilename )
97+ cutPrefix := sle .addDir (entry .ScriptFilename )
9398 for i := range entry .Stacktrace {
94- sle .addDir (entry .Stacktrace [i ].Path )
99+ cutPrefix = cutPrefix && sle .addDir (entry .Stacktrace [i ].Path )
95100 }
96101
97- pathOffset := sle .longestCommonPrefOffset ()
102+ pathOffset := 0
103+ if cutPrefix {
104+ pathOffset = sle .longestCommonPrefOffset ()
105+ }
98106
99107 return []zap.Field {
100108 zap .String ("filename" , entry .ScriptFilename [pathOffset :]),
0 commit comments