-
Notifications
You must be signed in to change notification settings - Fork 17
/
glg.go
executable file
·1524 lines (1332 loc) · 34.3 KB
/
glg.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// MIT License
//
// Copyright (c) 2019 kpango (Yusuke Kato)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Package glg can quickly output that are colored and leveled logs with simple syntax
package glg
import (
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"math"
"net/http"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
json "github.com/goccy/go-json"
"github.com/kpango/fastime"
)
// Glg is glg base struct
type Glg struct {
bs *uint64
logger loggers
levelCounter *uint32
levelMap levelMap
buffer sync.Pool
callerDepth int
enableJSON bool
}
// JSONFormat is json object structure for logging
type JSONFormat struct {
Date string `json:"date,omitempty"`
Level string `json:"level,omitempty"`
File string `json:"file,omitempty"`
Detail interface{} `json:"detail,omitempty"`
}
// MODE is logging mode (std only, writer only, std & writer)
type MODE uint8
// LEVEL is log level
type LEVEL uint8
type wMode uint8
type traceMode int64
type logger struct {
tag string
rawtag []byte
writer io.Writer
std io.Writer
color func(string) string
isColor bool
traceMode traceMode
mode MODE
prevMode MODE
writeMode wMode
disableTimestamp bool
}
const (
// DEBG is debug log level
DEBG LEVEL = iota + 1
// TRACE is trace log level
TRACE
// PRINT is print log level
PRINT
// LOG is log level
LOG
// INFO is info log level
INFO
// OK is success notify log level
OK
// WARN is warning log level
WARN
// ERR is error log level
ERR
// FAIL is failed log level
FAIL
// FATAL is fatal log level
FATAL
// UNKNOWN is unknown log level
UNKNOWN LEVEL = LEVEL(math.MaxUint8)
// NONE is disable Logging
NONE MODE = iota + 1
// STD is std log mode
STD
// BOTH is both log mode
BOTH
// WRITER is io.Writer log mode
WRITER
// Internal writeMode
writeColorStd wMode = iota + 1
writeStd
writeWriter
writeColorBoth
writeBoth
none
// Default Format
df = "%v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v " +
"%v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v " +
"%v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v " +
"%v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v %v "
dfl = len(df) / 3
timeFormat = "2006-01-02 15:04:05"
// return code
rc = "\n"
rcl = len(rc)
tab = "\t"
lsep = tab + "["
lsepl = len(lsep)
sep = "]:" + tab
sepl = len(sep)
TraceLineNone traceMode = 1 << iota
TraceLineShort
TraceLineLong
DefaultCallerDepth = 2
)
var (
glg *Glg
once sync.Once
// exit for Faltal error
exit = os.Exit
)
func init() {
Get()
}
func (l LEVEL) String() string {
switch l {
case DEBG:
return "DEBG"
case TRACE:
return "TRACE"
case PRINT:
return "PRINT"
case LOG:
return "LOG"
case INFO:
return "INFO"
case OK:
return "OK"
case WARN:
return "WARN"
case ERR:
return "ERR"
case FAIL:
return "FAIL"
case FATAL:
return "FATAL"
}
return ""
}
func (l *logger) updateMode() *logger {
switch {
case l.mode == WRITER && l.writer != nil:
l.writeMode = writeWriter
case l.mode == BOTH && l.isColor && l.writer != nil:
l.writeMode = writeColorBoth
case l.mode == BOTH && !l.isColor && l.writer != nil:
l.writeMode = writeBoth
case l.isColor && ((l.mode == BOTH && l.writer == nil) || l.mode == STD):
l.writeMode = writeColorStd
case !l.isColor && ((l.mode == BOTH && l.writer == nil) || l.mode == STD):
l.writeMode = writeStd
default:
l.writeMode = none
}
return l
}
// New returns plain glg instance
func New() *Glg {
g := &Glg{
levelCounter: new(uint32),
callerDepth: DefaultCallerDepth,
}
g.bs = new(uint64)
atomic.StoreUint64(g.bs, uint64(len(timeFormat)+lsepl+sepl))
g.buffer = sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 0, int(atomic.LoadUint64(g.bs))))
},
}
atomic.StoreUint32(g.levelCounter, uint32(FATAL))
for lev, log := range map[LEVEL]*logger{
// standard out
DEBG: {
std: os.Stdout,
color: Purple,
isColor: true,
mode: STD,
traceMode: TraceLineNone,
},
TRACE: {
std: os.Stdout,
color: Yellow,
isColor: true,
mode: STD,
traceMode: TraceLineNone,
},
PRINT: {
std: os.Stdout,
color: Colorless,
isColor: true,
mode: STD,
traceMode: TraceLineNone,
},
LOG: {
std: os.Stdout,
color: Colorless,
isColor: true,
mode: STD,
traceMode: TraceLineNone,
},
INFO: {
std: os.Stdout,
color: Green,
isColor: true,
mode: STD,
traceMode: TraceLineNone,
},
OK: {
std: os.Stdout,
color: Cyan,
isColor: true,
mode: STD,
traceMode: TraceLineNone,
},
WARN: {
std: os.Stdout,
color: Orange,
isColor: true,
mode: STD,
traceMode: TraceLineNone,
},
// error out
ERR: {
std: os.Stderr,
color: Red,
isColor: true,
mode: STD,
traceMode: TraceLineShort,
},
FAIL: {
std: os.Stderr,
color: Red,
isColor: true,
mode: STD,
traceMode: TraceLineShort,
},
FATAL: {
std: os.Stderr,
color: Red,
isColor: true,
mode: STD,
traceMode: TraceLineLong,
},
} {
log.tag = lev.String()
log.rawtag = []byte(lsep + log.tag + sep)
log.prevMode = log.mode
log.updateMode()
g.logger.Store(lev, log)
}
return g
}
// Get returns singleton glg instance
func Get() *Glg {
once.Do(func() {
fastime.SetFormat(timeFormat)
glg = New()
})
return glg
}
func (g *Glg) EnableJSON() *Glg {
g.enableJSON = true
return g
}
func (g *Glg) DisableJSON() *Glg {
g.enableJSON = false
return g
}
func (g *Glg) EnablePoolBuffer(size int) *Glg {
for range make([]struct{}, size) {
g.buffer.Put(g.buffer.Get().(*bytes.Buffer))
}
return g
}
// SetLevel sets glg global log level
func (g *Glg) SetLevel(lv LEVEL) *Glg {
g.logger.Range(func(lev LEVEL, l *logger) bool {
if lev < lv {
l.prevMode = l.mode
l.mode = NONE
} else {
l.mode = l.prevMode
}
l.updateMode()
g.logger.Store(lev, l)
return true
})
return g
}
// SetMode sets glg logging mode
func (g *Glg) SetMode(mode MODE) *Glg {
g.logger.Range(func(lev LEVEL, l *logger) bool {
l.mode = mode
l.prevMode = mode
l.updateMode()
g.logger.Store(lev, l)
return true
})
return g
}
// SetLevelMode sets glg logging mode* per level
func (g *Glg) SetLevelMode(level LEVEL, mode MODE) *Glg {
l, ok := g.logger.Load(level)
if ok {
l.mode = mode
l.prevMode = mode
l.updateMode()
g.logger.Store(level, l)
}
return g
}
// SetPrefix sets Print logger prefix
func SetPrefix(lev LEVEL, pref string) *Glg {
return glg.SetPrefix(lev, pref)
}
// SetPrefix sets Print logger prefix
func (g *Glg) SetPrefix(lev LEVEL, pref string) *Glg {
l, ok := g.logger.Load(lev)
if ok {
l.tag = pref
l.rawtag = []byte(lsep + l.tag + sep)
g.logger.Store(lev, l)
}
return g
}
// GetCurrentMode returns current logging mode
func (g *Glg) GetCurrentMode(level LEVEL) MODE {
l, ok := g.logger.Load(level)
if ok {
return l.mode
}
return NONE
}
// InitWriter is initialize glg writer
func (g *Glg) InitWriter() *Glg {
g.logger.Range(func(lev LEVEL, l *logger) bool {
l.writer = nil
l.updateMode()
g.logger.Store(lev, l)
return true
})
return g
}
// SetWriter sets writer to glg std writers
func (g *Glg) SetWriter(writer io.Writer) *Glg {
if writer == nil {
return g
}
g.logger.Range(func(lev LEVEL, l *logger) bool {
l.writer = writer
l.updateMode()
g.logger.Store(lev, l)
return true
})
return g
}
// AddWriter adds writer to glg std writers
func (g *Glg) AddWriter(writer io.Writer) *Glg {
if writer == nil {
return g
}
g.logger.Range(func(lev LEVEL, l *logger) bool {
if l.writer == nil {
l.writer = writer
} else {
l.writer = io.MultiWriter(l.writer, writer)
}
l.updateMode()
g.logger.Store(lev, l)
return true
})
return g
}
// SetLevelColor sets the color for each level
func (g *Glg) SetLevelColor(level LEVEL, color func(string) string) *Glg {
l, ok := g.logger.Load(level)
if ok {
l.color = color
g.logger.Store(level, l)
}
return g
}
// SetLevelWriter sets writer to glg std writer per logging level
func (g *Glg) SetLevelWriter(level LEVEL, writer io.Writer) *Glg {
if writer == nil {
return g
}
l, ok := g.logger.Load(level)
if ok {
l.writer = writer
l.updateMode()
g.logger.Store(level, l)
}
return g
}
// AddLevelWriter adds writer to glg std writer per logging level
func (g *Glg) AddLevelWriter(level LEVEL, writer io.Writer) *Glg {
if writer == nil {
return g
}
l, ok := g.logger.Load(level)
if ok {
if l.writer != nil {
l.writer = io.MultiWriter(l.writer, writer)
} else {
l.writer = writer
}
l.updateMode()
g.logger.Store(level, l)
}
return g
}
// AddStdLevel adds std log level and returns LEVEL
func (g *Glg) AddStdLevel(tag string, mode MODE, isColor bool) *Glg {
return g.addLevel(tag, mode, isColor, os.Stdout)
}
// AddErrLevel adds error log level and returns LEVEL
func (g *Glg) AddErrLevel(tag string, mode MODE, isColor bool) *Glg {
return g.addLevel(tag, mode, isColor, os.Stderr)
}
func (g *Glg) addLevel(tag string, mode MODE, isColor bool, std io.Writer) *Glg {
lev := LEVEL(atomic.AddUint32(g.levelCounter, 1))
tag = strings.ToUpper(tag)
g.levelMap.Store(tag, lev)
l := &logger{
writer: nil,
std: std,
color: Colorless,
isColor: isColor,
mode: mode,
prevMode: mode,
tag: tag,
rawtag: []byte(lsep + tag + sep),
}
l.updateMode()
g.logger.Store(lev, l)
return g
}
// SetTimeLocation configures specific time location
func (g *Glg) SetTimeLocation(loc *time.Location) *Glg {
if loc != nil {
fastime.SetLocation(loc)
}
return g
}
// GetTimeLocation configures specific time location
func (g *Glg) GetTimeLocation() (loc *time.Location) {
return fastime.GetLocation()
}
// EnableTimestamp enables timestamp output
func (g *Glg) EnableTimestamp() *Glg {
g.logger.Range(func(lev LEVEL, l *logger) bool {
l.disableTimestamp = false
g.logger.Store(lev, l)
return true
})
return g
}
// DisableTimestamp disables timestamp output
func (g *Glg) DisableTimestamp() *Glg {
g.logger.Range(func(lev LEVEL, l *logger) bool {
l.disableTimestamp = true
g.logger.Store(lev, l)
return true
})
return g
}
// EnableLevelTimestamp enables timestamp output
func (g *Glg) EnableLevelTimestamp(lv LEVEL) *Glg {
l, ok := g.logger.Load(lv)
if ok {
l.disableTimestamp = false
g.logger.Store(lv, l)
}
return g
}
// DisableLevelTimestamp disables timestamp output
func (g *Glg) DisableLevelTimestamp(lv LEVEL) *Glg {
l, ok := g.logger.Load(lv)
if ok {
l.disableTimestamp = true
g.logger.Store(lv, l)
}
return g
}
// SetCallerDepth configures output line trace caller depth
func (g *Glg) SetCallerDepth(depth int) *Glg {
if depth > DefaultCallerDepth {
g.callerDepth = depth
}
return g
}
// SetLineTraceMode configures output line traceFlag
func (g *Glg) SetLineTraceMode(mode traceMode) *Glg {
g.logger.Range(func(lev LEVEL, l *logger) bool {
l.traceMode = mode
g.logger.Store(lev, l)
return true
})
return g
}
// SetLevelLineTraceMode configures output line traceFlag
func (g *Glg) SetLevelLineTraceMode(lv LEVEL, mode traceMode) *Glg {
l, ok := g.logger.Load(lv)
if ok {
l.traceMode = mode
g.logger.Store(lv, l)
}
return g
}
// EnableColor enables color output
func (g *Glg) EnableColor() *Glg {
g.logger.Range(func(lev LEVEL, l *logger) bool {
l.isColor = true
l.updateMode()
g.logger.Store(lev, l)
return true
})
return g
}
// DisableColor disables color output
func (g *Glg) DisableColor() *Glg {
g.logger.Range(func(lev LEVEL, l *logger) bool {
l.isColor = false
l.updateMode()
g.logger.Store(lev, l)
return true
})
return g
}
// EnableLevelColor enables color output
func (g *Glg) EnableLevelColor(lv LEVEL) *Glg {
l, ok := g.logger.Load(lv)
if ok {
l.isColor = true
l.updateMode()
g.logger.Store(lv, l)
}
return g
}
// DisableLevelColor disables color output
func (g *Glg) DisableLevelColor(lv LEVEL) *Glg {
l, ok := g.logger.Load(lv)
if ok {
l.isColor = false
l.updateMode()
g.logger.Store(lv, l)
}
return g
}
// RawString returns raw log string exclude time & tags
func (g *Glg) RawString(data []byte) string {
str := *(*string)(unsafe.Pointer(&data))
return str[strings.Index(str, sep)+sepl : len(str)-rcl]
}
// RawString returns raw log string exclude time & tags
func RawString(data []byte) string {
return glg.RawString(data)
}
// Atol converts level string to Glg.LEVEL
func (g *Glg) Atol(tag string) LEVEL {
return g.TagStringToLevel(tag)
}
// Atol converts level string to Glg.LEVEL
func Atol(tag string) LEVEL {
return glg.TagStringToLevel(tag)
}
// TagStringToLevel converts level string to Glg.LEVEL
func (g *Glg) TagStringToLevel(tag string) LEVEL {
tag = strings.TrimSpace(strings.ToUpper(tag))
lv, ok := g.levelMap.Load(tag)
if ok {
return lv
}
switch tag {
case DEBG.String(), "DBG", "DEBUG", "D":
return DEBG
case TRACE.String(), "TRC", "TRA", "TR", "T":
return TRACE
case PRINT.String(), "PRINT", "PNT", "P":
return PRINT
case LOG.String(), "LO", "LG", "L":
return LOG
case INFO.String(), "IFO", "INF", "I":
return INFO
case OK.String(), "O", "K":
return OK
case WARN.String(), "WARNING", "WRN", "W":
return WARN
case ERR.String(), "ERROR", "ER", "E":
return ERR
case FAIL.String(), "FAILED", "FI":
return FAIL
case FATAL.String(), "FAT", "FL", "F":
return FATAL
}
return UNKNOWN
}
// TagStringToLevel converts level string to glg.LEVEL
func TagStringToLevel(tag string) LEVEL {
return glg.TagStringToLevel(tag)
}
func OpenFile(path string, flg int, perm fs.FileMode) (file *os.File, err error) {
if path == "" {
return nil, errors.New("file path argument must not be empty")
}
defer func() {
if err != nil && file != nil {
err = errors.Join(file.Close(), err)
file = nil
}
}()
if ffi, err := os.Stat(path); err != nil {
dir := filepath.Dir(path)
fi, err := os.Stat(dir)
if err != nil {
err = os.MkdirAll(dir, perm)
if err != nil {
err = fmt.Errorf("failed to make directory %s using os.MkdirAll operation\tdir info: %s: %w", dir, fitos(dir, fi), err)
return nil, err
}
}
if flg&(os.O_CREATE|os.O_APPEND) > 0 {
file, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_TRUNC, perm)
if err != nil {
err = fmt.Errorf("failed to create file %s using os.Create operation\tfile info: %s: %w", path, fitos(path, ffi), err)
if file != nil {
return nil, errors.Join(err, file.Close())
}
return nil, err
}
if file != nil {
err = file.Close()
if err != nil {
fi, ferr := file.Stat()
if ferr == nil && fi != nil {
return nil, fmt.Errorf("failed to close file %s\tfile info: %s: %w", path, fitos(path, fi), err)
}
return nil, errors.Join(err, ferr)
}
}
}
}
file, err = os.OpenFile(path, flg, perm)
if err != nil {
err = fmt.Errorf("failed to open file %s using os.OpenFile operation with configuration, flg: %d, perm: %s\tfile info: %s: %w", path, flg, perm.String(), fitos(path, nil), err)
if file != nil {
return nil, errors.Join(err, file.Close())
}
return nil, err
}
return file, nil
}
func fitos(path string, fi os.FileInfo) string {
if fi == nil {
var err error
fi, err = os.Stat(path)
if err != nil || fi == nil {
return fmt.Sprintf("unknown file info: for %s\t%v", path, fi)
}
}
if fi != nil {
return fmt.Sprintf("{name: %s, size: %d, mode: %s, mode_int: %d, is_dir: %v}",
fi.Name(),
fi.Size(),
fi.Mode().String(),
fi.Mode(),
fi.IsDir(),
)
}
return fmt.Sprintf("unknown file info: %v", fi)
}
// FileWriter generates *osFile -> io.Writer
func FileWriter(path string, perm os.FileMode) *os.File {
f, err := OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, perm)
if err != nil {
return nil
}
return f
}
// HTTPLogger is simple http access logger
func (g *Glg) HTTPLogger(name string, handler http.Handler) http.Handler {
return g.HTTPLoggerFunc(name, handler.ServeHTTP)
}
// HTTPLoggerFunc is simple http access logger
func (g *Glg) HTTPLoggerFunc(name string, hf http.HandlerFunc) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := fastime.UnixNanoNow()
hf(w, r)
start -= fastime.UnixNanoNow()
err := g.Logf("Method: %s\tURI: %s\tName: %s\tTime: %s",
r.Method, r.RequestURI, name, (*(*time.Duration)(unsafe.Pointer(&start))).String())
if err != nil {
err = g.Error(err)
if err != nil {
fmt.Println(err)
}
}
})
}
// HTTPLogger is simple http access logger
func HTTPLogger(name string, handler http.Handler) http.Handler {
return glg.HTTPLogger(name, handler)
}
// HTTPLoggerFunc is simple http access logger
func HTTPLoggerFunc(name string, hf http.HandlerFunc) http.Handler {
return glg.HTTPLoggerFunc(name, hf)
}
// Colorless returns colorless string
func Colorless(str string) string {
return str
}
func colorString(code, str string) string {
return "\033["+code+"m" + str + "\033[39m"
}
// Red returns red colored string
func Red(str string) string {
return colorString("31", str)
}
// Green returns green colored string
func Green(str string) string {
return colorString("32", str)
}
// Orange returns orange colored string
func Orange(str string) string {
return colorString("33", str)
}
// Purple returns purple colored string
func Purple(str string) string {
return colorString("34", str)
}
// Cyan returns cyan colored string
func Cyan(str string) string {
return colorString("36", str)
}
// Yellow returns yellow colored string
func Yellow(str string) string {
return colorString("93", str)
}
// Brown returns Brown colored string
func Brown(str string) string {
return colorString("96", str)
}
// Gray returns Gray colored string
func Gray(str string) string {
return colorString("90", str)
}
// Black returns Black colored string
func Black(str string) string {
return colorString("30", str)
}
// White returns white colored string
func White(str string) string {
return colorString("97", str)
}
func (g *Glg) out(level LEVEL, format string, val ...interface{}) error {
log, ok := g.logger.Load(level)
if !ok {
return fmt.Errorf("error:\tLog Level %d Not Found", level)
}
if log.mode == NONE {
return nil
}
var fl string
if log.traceMode&(TraceLineLong|TraceLineShort) != 0 {
_, file, line, ok := runtime.Caller(g.callerDepth)
switch {
case !ok:
fl = "???:0"
case log.traceMode&TraceLineShort != 0:
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
file = file[i+1:]
break
}
}
fl = file + ":" + strconv.Itoa(line)
case strings.HasPrefix(file, runtime.GOROOT()+"/src"):
fl = "https://github.com/golang/go/blob/" + runtime.Version() + strings.TrimPrefix(file, runtime.GOROOT()) + "#L" + strconv.Itoa(line)
case strings.Contains(file, "go/pkg/mod/"):
fl = "https:/"
for _, path := range strings.Split(strings.SplitN(file, "go/pkg/mod/", 2)[1], "/") {
left, right, ok := strings.Cut(path, "@")
if ok {
if strings.Count(right, "-") > 2 {
path = left + "/blob/main"
} else {
path = left + "/blob/" + right
}
}
fl += "/" + path
}
fl += "#L" + strconv.Itoa(line)
case strings.Contains(file, "go/src"):
fl = "https:/"
cnt := 0
for _, path := range strings.Split(strings.SplitN(file, "go/src/", 2)[1], "/") {
if cnt == 3 {
path = "blob/main/" + path
}
fl += "/" + path
cnt++
}
fl += "#L" + strconv.Itoa(line)
default:
fl = file + ":" + strconv.Itoa(line)
}
}
if g.enableJSON {
var w io.Writer
switch log.writeMode {
case writeStd, writeColorStd:
w = log.std
case writeWriter:
w = log.writer
case writeBoth, writeColorBoth:
w = io.MultiWriter(log.std, log.writer)
default:
return nil
}
var detail interface{}
if format != "" {
detail = fmt.Sprintf(format, val...)
} else if len(val) > 1 {
detail = val
} else {
detail = val[0]
}
var timestamp string
if !log.disableTimestamp {
fn := fastime.FormattedNow()
timestamp = *(*string)(unsafe.Pointer(&fn))
}
return json.NewEncoder(w).Encode(JSONFormat{
Date: timestamp,
Level: log.tag,
File: fl,
Detail: detail,
})
}
var (
buf []byte
err error
b = g.buffer.Get().(*bytes.Buffer)
)
if log.disableTimestamp {
b.Write(log.rawtag[len(tab):])
} else {
b.Write(fastime.FormattedNow())
b.Write(log.rawtag)
}
if len(fl) != 0 {