9
9
"strings"
10
10
11
11
e "github.com/Authentura/codectrl-go-logger/error"
12
- "github.com/Authentura/codectrl-go-logger/hashbag"
12
+ h "github.com/Authentura/codectrl-go-logger/hashbag"
13
13
14
14
b "github.com/Authentura/codectrl-go-protobufs/data/backtrace_data"
15
15
l "github.com/Authentura/codectrl-go-protobufs/data/log"
@@ -21,7 +21,7 @@ import (
21
21
type createLogParams struct {
22
22
surround uint32
23
23
functionName string
24
- functionNameOccurences hashbag .HashBag [string ]
24
+ functionNameOccurences h .HashBag [string ]
25
25
}
26
26
27
27
func createLog (message string , params ... createLogParams ) (* l.Log , error ) {
@@ -39,6 +39,8 @@ func createLog(message string, params ...createLogParams) (*l.Log, error) {
39
39
}
40
40
}
41
41
42
+ parameters := params [0 ]
43
+
42
44
log := l.Log {
43
45
Uuid : "" ,
44
46
Stack : []* b.BacktraceData {},
@@ -68,6 +70,13 @@ func createLog(message string, params ...createLogParams) (*l.Log, error) {
68
70
if last != nil {
69
71
log .LineNumber = last .GetLineNumber ()
70
72
log .FileName = last .GetFilePath ()
73
+ snippet , err := getCodeSnippet (last .FilePath , & log , parameters .surround , "" , nil )
74
+
75
+ if err != nil {
76
+ return nil , errors .Wrap (err , 0 )
77
+ }
78
+
79
+ log .CodeSnippet = * snippet
71
80
}
72
81
73
82
return & log , nil
@@ -286,4 +295,43 @@ func getCode(filePath string, lineNumber uint32) (*string, error) {
286
295
return & line , nil
287
296
}
288
297
289
- // TODO: Add code snippet retrieval function
298
+ // TODO: Account for batch logging
299
+
300
+ func getCodeSnippet (filePath string , log * l.Log , surround uint32 , functionName string , functionNameOccurences * h.HashBag [string ]) (* map [uint32 ]string , error ) {
301
+ file , err := os .Open (filePath )
302
+ lineNumber := int (log .LineNumber )
303
+ offsetLine := lineNumber - int (surround )
304
+
305
+ if offsetLine < 0 {
306
+ offsetLine = 0
307
+ }
308
+
309
+ if err != nil {
310
+ return nil , errors .Wrap (err , 0 )
311
+ }
312
+
313
+ defer file .Close ()
314
+
315
+ contentBytes , err := io .ReadAll (file )
316
+
317
+ if err != nil {
318
+ return nil , errors .Wrap (err , 0 )
319
+ }
320
+
321
+ content := string (contentBytes )
322
+ lines := strings .Split (content , "\n " )
323
+
324
+ snippet := map [uint32 ]string {}
325
+
326
+ for index , line := range lines {
327
+ if index < offsetLine {
328
+ continue
329
+ } else if index > lineNumber + int (surround ) {
330
+ break
331
+ }
332
+
333
+ snippet [uint32 (index + 1 )] = line
334
+ }
335
+
336
+ return & snippet , nil
337
+ }
0 commit comments