@@ -45,6 +45,48 @@ type Result struct {
4545 Values []interface {} `json:"values"`
4646}
4747
48+ // parseLokiTimeParam 将 LogQueryOptions.StartAt/EndAt 转换为 Unix 时间戳(秒)。
49+ // 支持 int64/int32/int(Unix 秒)以及字符串(Unix 秒数字符串或 RFC3339Nano 格式)。
50+ // 当传入值为空或无法解析时,返回 (0, false)。
51+ func parseLokiTimeParam (v interface {}) (int64 , bool ) {
52+ switch val := v .(type ) {
53+ case int64 :
54+ if val == 0 {
55+ return 0 , false
56+ }
57+ return val , true
58+ case int32 :
59+ if val == 0 {
60+ return 0 , false
61+ }
62+ return int64 (val ), true
63+ case int :
64+ if val == 0 {
65+ return 0 , false
66+ }
67+ return int64 (val ), true
68+ case string :
69+ if val == "" {
70+ return 0 , false
71+ }
72+ // 尝试解析为 Unix 时间戳字符串
73+ if unix , err := strconv .ParseInt (val , 10 , 64 ); err == nil {
74+ return unix , true
75+ }
76+ // 尝试解析为 RFC3339Nano 格式
77+ if t , err := time .Parse (time .RFC3339Nano , val ); err == nil {
78+ return t .Unix (), true
79+ }
80+ // 尝试解析为 RFC3339 格式
81+ if t , err := time .Parse (time .RFC3339 , val ); err == nil {
82+ return t .Unix (), true
83+ }
84+ return 0 , false
85+ default :
86+ return 0 , false
87+ }
88+ }
89+
4890func (l LokiProvider ) Query (options LogQueryOptions ) (Logs , int , error ) {
4991 curTime := time .Now ()
5092
@@ -60,16 +102,18 @@ func (l LokiProvider) Query(options LogQueryOptions) (Logs, int, error) {
60102 options .Loki .Limit = 100
61103 }
62104
63- if options .StartAt == "" {
105+ startAt , ok := parseLokiTimeParam (options .StartAt )
106+ if ! ok {
64107 duration , _ := time .ParseDuration (strconv .Itoa (1 ) + "h" )
65- options . StartAt = curTime .Add (- duration ).Format ( time . RFC3339Nano )
108+ startAt = curTime .Add (- duration ).Unix ( )
66109 }
67110
68- if options .EndAt == "" {
69- options .EndAt = curTime .Format (time .RFC3339Nano )
111+ endAt , ok := parseLokiTimeParam (options .EndAt )
112+ if ! ok {
113+ endAt = curTime .Unix ()
70114 }
71115
72- args := fmt .Sprintf ("/loki/api/v1/query_range?query=%s&direction=%s&limit=%d&start=%d&end=%d" , url .QueryEscape (options .Loki .Query ), options .Loki .Direction , options .Loki .Limit , options . StartAt .( int64 ), options . EndAt .( int64 ) )
116+ args := fmt .Sprintf ("/loki/api/v1/query_range?query=%s&direction=%s&limit=%d&start=%d&end=%d" , url .QueryEscape (options .Loki .Query ), options .Loki .Direction , options .Loki .Limit , startAt , endAt )
73117 requestURL := l .Url + args
74118
75119 var headers = make (map [string ]string )
0 commit comments