Skip to content

Commit

Permalink
feat: add from/to flags to get logs in an absolute timeframe
Browse files Browse the repository at this point in the history
This adds two new flags that when set, override the since parameter to
only show logs in this absolute time frame. This can be useful when
looking for logs beyond the (server-side) line limit of 5000 lines.
  • Loading branch information
ctrox committed Feb 7, 2025
1 parent 61c228c commit b3695ac
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
16 changes: 13 additions & 3 deletions logs/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ type logsCmd struct {
Follow bool `help:"Follow the logs by live tailing." short:"f"`
Lines int `help:"Amount of lines to output" default:"50" short:"l"`
Since time.Duration `help:"Duration how long to look back for logs" short:"s" default:"${log_retention}"`
From time.Time `help:"Ignore since flag and start looking for logs at this absolute time (RFC3339)" placeholder:"2025-01-01T14:00:00+01:00"`
To time.Time `help:"Ignore since flag and stop looking for logs at this absolute time (RFC3339)" placeholder:"2025-01-01T15:00:00+01:00"`
Output string `help:"Configures the log output format. ${enum}" short:"o" enum:"default,json" default:"default"`
NoLabels bool `help:"disable labels in log output"`
out output.LogOutput
Expand All @@ -34,15 +36,23 @@ type logsCmd struct {
var logRetention = time.Duration(time.Hour * 24 * 30)

func (cmd *logsCmd) Run(ctx context.Context, client *api.Client, queryString string, labels ...string) error {
if cmd.Since > logRetention {
now := time.Now()
start, end := now.Add(-cmd.Since), now
if !cmd.From.IsZero() {
start = cmd.From
}
if !cmd.To.IsZero() {
end = cmd.To
}
if now.Sub(start) > logRetention {
return fmt.Errorf("the logs requested exceed the retention period of %.f days", logRetention.Hours()/24)
}

query := log.Query{
QueryString: queryString,
Limit: cmd.Lines,
Start: time.Now().Add(-cmd.Since),
End: time.Now(),
Start: start,
End: end,
Direction: logproto.BACKWARD,
Quiet: true,
}
Expand Down
19 changes: 19 additions & 0 deletions logs/logs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,25 @@ func TestRun(t *testing.T) {
},
expectedErrContains: "the logs requested exceed the retention period",
},
"from/to flags override since": {
cmd: logsCmd{
Output: "default",
Lines: len(lines),
Since: logRetention * 2,
From: time.Now().Add(-time.Hour),
To: time.Now(),
},
expectedLines: len(lines),
},
"from flag alone overrides since": {
cmd: logsCmd{
Output: "default",
Lines: len(lines),
Since: logRetention * 2,
From: time.Now().Add(-time.Hour),
},
expectedLines: len(lines),
},
}

for name, tc := range cases {
Expand Down

0 comments on commit b3695ac

Please sign in to comment.