Skip to content

Commit 5249a5c

Browse files
JakeCooperclaude
andauthored
feat: add --since and --until flags to logs command (#724)
* feat: add --since and --until flags to logs command Add timestamp-based filtering to the logs command: - --since (-S): Show logs since a specific time - --until (-U): Show logs until a specific time Supports relative times (30s, 5m, 2h, 1d, 1w) and ISO 8601 timestamps. Examples: railway logs --since 1h railway logs --since 30m --until 10m railway logs --since 2024-01-15T10:00:00Z Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * style: fix cargo fmt issues --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
1 parent e78f6c0 commit 5249a5c

6 files changed

Lines changed: 182 additions & 9 deletions

File tree

‎src/commands/logs.rs‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use crate::{
66
environment::get_matched_environment,
77
project::{ensure_project_and_environment_exist, get_project},
88
},
9-
util::logs::print_log,
9+
util::{logs::print_log, time::parse_time},
1010
};
1111
use anyhow::bail;
1212

@@ -18,12 +18,15 @@ use super::{
1818
#[derive(Parser)]
1919
#[clap(
2020
about = "View build or deploy logs from a Railway deployment",
21-
long_about = "View build or deploy logs from a Railway deployment. This will stream logs by default, or fetch historical logs if the --lines flag is provided.",
21+
long_about = "View build or deploy logs from a Railway deployment. This will stream logs by default, or fetch historical logs if the --lines, --since, or --until flags are provided.",
2222
after_help = "Examples:
2323
2424
railway logs # Stream live logs from latest deployment
2525
railway logs --build 7422c95b-c604-46bc-9de4-b7a43e1fd53d # Stream build logs from a specific deployment
2626
railway logs --lines 100 # Pull last 100 logs without streaming
27+
railway logs --since 1h # View logs from the last hour
28+
railway logs --since 30m --until 10m # View logs from 30 minutes ago until 10 minutes ago
29+
railway logs --since 2024-01-15T10:00:00Z # View logs since a specific timestamp
2730
railway logs --service backend --environment production # Stream latest deployment logs from a specific service in a specific environment
2831
railway logs --lines 10 --filter \"@level:error\" # View 10 latest error logs
2932
railway logs --lines 10 --filter \"@level:warn AND rate limit\" # View 10 latest warning logs related to rate limiting
@@ -67,6 +70,14 @@ pub struct Args {
6770
/// Always show logs from the latest deployment, even if it failed or is still building
6871
#[clap(long)]
6972
latest: bool,
73+
74+
/// Show logs since a specific time (disables streaming). Accepts relative times (e.g., 30s, 5m, 2h, 1d, 1w) or ISO 8601 timestamps (e.g., 2024-01-15T10:30:00Z)
75+
#[clap(long, short = 'S', value_name = "TIME")]
76+
since: Option<String>,
77+
78+
/// Show logs until a specific time (disables streaming). Same formats as --since
79+
#[clap(long, short = 'U', value_name = "TIME")]
80+
until: Option<String>,
7081
}
7182

7283
pub async fn command(args: Args) -> Result<()> {
@@ -76,8 +87,19 @@ pub async fn command(args: Args) -> Result<()> {
7687

7788
ensure_project_and_environment_exist(&client, &configs, &linked_project).await?;
7889

79-
// Stream only if no line limit is specified and running in a terminal
80-
let should_stream = args.lines.is_none() && std::io::stdout().is_terminal();
90+
let start_date = args.since.as_ref().map(|s| parse_time(s)).transpose()?;
91+
let end_date = args.until.as_ref().map(|s| parse_time(s)).transpose()?;
92+
93+
if let (Some(s), Some(e)) = (&start_date, &end_date) {
94+
if s >= e {
95+
bail!("--since time must be before --until time");
96+
}
97+
}
98+
99+
let has_time_filter = start_date.is_some() || end_date.is_some();
100+
101+
// Stream only if no line limit or time filter is specified and running in a terminal
102+
let should_stream = args.lines.is_none() && !has_time_filter && std::io::stdout().is_terminal();
81103

82104
let project = get_project(&client, &configs, linked_project.project.clone()).await?;
83105

@@ -162,6 +184,8 @@ pub async fn command(args: Args) -> Result<()> {
162184
deployment_id.clone(),
163185
args.lines.or(Some(500)),
164186
args.filter.clone(),
187+
start_date,
188+
end_date,
165189
|log| print_log(log, args.json, false), // Build logs use simple output
166190
)
167191
.await?;
@@ -178,6 +202,8 @@ pub async fn command(args: Args) -> Result<()> {
178202
deployment_id.clone(),
179203
args.lines.or(Some(500)),
180204
args.filter.clone(),
205+
start_date,
206+
end_date,
181207
|log| print_log(log, args.json, true), // Deploy logs use formatted output
182208
)
183209
.await?;

‎src/controllers/deployment.rs‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use crate::{
88
util::retry::RetryConfig,
99
};
1010
use anyhow::{Context, Result};
11+
use chrono::{DateTime, Utc};
1112
use futures::StreamExt;
1213
use reqwest::Client;
1314
use std::time::Duration;
@@ -39,12 +40,15 @@ pub async fn fetch_build_logs(
3940
deployment_id: String,
4041
limit: Option<i64>,
4142
filter: Option<String>,
43+
start_date: Option<DateTime<Utc>>,
44+
end_date: Option<DateTime<Utc>>,
4245
on_log: impl Fn(queries::build_logs::BuildLogsBuildLogs),
4346
) -> Result<()> {
4447
let vars = queries::build_logs::Variables {
4548
deployment_id,
4649
limit,
47-
start_date: None,
50+
start_date,
51+
end_date,
4852
filter,
4953
};
5054

@@ -67,12 +71,16 @@ pub async fn fetch_deploy_logs(
6771
deployment_id: String,
6872
limit: Option<i64>,
6973
filter: Option<String>,
74+
start_date: Option<DateTime<Utc>>,
75+
end_date: Option<DateTime<Utc>>,
7076
on_log: impl Fn(queries::deployment_logs::LogFields),
7177
) -> Result<()> {
7278
let vars = queries::deployment_logs::Variables {
7379
deployment_id,
7480
limit,
7581
filter,
82+
start_date,
83+
end_date,
7684
};
7785

7886
let response = post_graphql::<queries::DeploymentLogs, _>(client, backboard, vars).await?;

‎src/gql/queries/strings/BuildLogs.graphql‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
query BuildLogs($deploymentId: String!, $limit: Int, $startDate: DateTime, $filter: String) {
2-
buildLogs(deploymentId: $deploymentId, limit: $limit, startDate: $startDate, filter: $filter) {
1+
query BuildLogs($deploymentId: String!, $limit: Int, $startDate: DateTime, $endDate: DateTime, $filter: String) {
2+
buildLogs(deploymentId: $deploymentId, limit: $limit, startDate: $startDate, endDate: $endDate, filter: $filter) {
33
...LogFields
44
}
55
}

‎src/gql/queries/strings/DeploymentLogs.graphql‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
query DeploymentLogs($deploymentId: String!, $limit: Int, $filter: String) {
2-
deploymentLogs(deploymentId: $deploymentId, limit: $limit, filter: $filter) {
1+
query DeploymentLogs($deploymentId: String!, $limit: Int, $filter: String, $startDate: DateTime, $endDate: DateTime) {
2+
deploymentLogs(deploymentId: $deploymentId, limit: $limit, filter: $filter, startDate: $startDate, endDate: $endDate) {
33
...LogFields
44
}
55
}

‎src/util/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@ pub mod logs;
44
pub mod progress;
55
pub mod prompt;
66
pub mod retry;
7+
pub mod time;
78
pub mod watcher;

‎src/util/time.rs‎

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
use anyhow::{Result, bail};
2+
use chrono::{DateTime, Duration, Local, TimeZone, Utc};
3+
4+
/// Parse a time string into a UTC DateTime.
5+
///
6+
/// Supports:
7+
/// - Relative times: "30s", "5m", "2h", "1d", "1w" (seconds, minutes, hours, days, weeks ago)
8+
/// - ISO 8601 with timezone: "2024-01-15T10:30:00Z" or "2024-01-15T10:30:00-05:00"
9+
/// - ISO 8601 without timezone (assumes local): "2024-01-15T10:30:00"
10+
pub fn parse_time(input: &str) -> Result<DateTime<Utc>> {
11+
let input = input.trim();
12+
13+
if let Some(dt) = parse_relative_time(input) {
14+
return Ok(dt);
15+
}
16+
17+
if let Ok(dt) = DateTime::parse_from_rfc3339(input) {
18+
return Ok(dt.with_timezone(&Utc));
19+
}
20+
21+
if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(input, "%Y-%m-%dT%H:%M:%S") {
22+
let local_dt = Local.from_local_datetime(&dt).single();
23+
if let Some(local_dt) = local_dt {
24+
return Ok(local_dt.with_timezone(&Utc));
25+
}
26+
}
27+
28+
if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(input, "%Y-%m-%d %H:%M:%S") {
29+
let local_dt = Local.from_local_datetime(&dt).single();
30+
if let Some(local_dt) = local_dt {
31+
return Ok(local_dt.with_timezone(&Utc));
32+
}
33+
}
34+
35+
if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(input, "%Y-%m-%d %H:%M") {
36+
let local_dt = Local.from_local_datetime(&dt).single();
37+
if let Some(local_dt) = local_dt {
38+
return Ok(local_dt.with_timezone(&Utc));
39+
}
40+
}
41+
42+
bail!(
43+
"Invalid time format: '{}'. Use relative time (e.g., 30m, 2h, 1d) or ISO 8601 (e.g., 2024-01-15T10:30:00Z)",
44+
input
45+
)
46+
}
47+
48+
fn parse_relative_time(input: &str) -> Option<DateTime<Utc>> {
49+
let input = input.to_lowercase();
50+
51+
if input.len() < 2 {
52+
return None;
53+
}
54+
55+
let (num_str, unit) = input.split_at(input.len() - 1);
56+
let num: i64 = num_str.parse().ok()?;
57+
58+
if num < 0 {
59+
return None;
60+
}
61+
62+
let duration = match unit {
63+
"s" => Duration::seconds(num),
64+
"m" => Duration::minutes(num),
65+
"h" => Duration::hours(num),
66+
"d" => Duration::days(num),
67+
"w" => Duration::weeks(num),
68+
_ => return None,
69+
};
70+
71+
Some(Utc::now() - duration)
72+
}
73+
74+
#[cfg(test)]
75+
mod tests {
76+
use super::*;
77+
78+
#[test]
79+
fn test_parse_relative_seconds() {
80+
let result = parse_time("30s").unwrap();
81+
let expected = Utc::now() - Duration::seconds(30);
82+
assert!((result - expected).num_seconds().abs() < 2);
83+
}
84+
85+
#[test]
86+
fn test_parse_relative_minutes() {
87+
let result = parse_time("5m").unwrap();
88+
let expected = Utc::now() - Duration::minutes(5);
89+
assert!((result - expected).num_seconds().abs() < 2);
90+
}
91+
92+
#[test]
93+
fn test_parse_relative_hours() {
94+
let result = parse_time("2h").unwrap();
95+
let expected = Utc::now() - Duration::hours(2);
96+
assert!((result - expected).num_seconds().abs() < 2);
97+
}
98+
99+
#[test]
100+
fn test_parse_relative_days() {
101+
let result = parse_time("1d").unwrap();
102+
let expected = Utc::now() - Duration::days(1);
103+
assert!((result - expected).num_seconds().abs() < 2);
104+
}
105+
106+
#[test]
107+
fn test_parse_relative_weeks() {
108+
let result = parse_time("2w").unwrap();
109+
let expected = Utc::now() - Duration::weeks(2);
110+
assert!((result - expected).num_seconds().abs() < 2);
111+
}
112+
113+
#[test]
114+
fn test_parse_iso8601_utc() {
115+
let result = parse_time("2024-01-15T10:30:00Z").unwrap();
116+
assert_eq!(result.to_rfc3339(), "2024-01-15T10:30:00+00:00");
117+
}
118+
119+
#[test]
120+
fn test_parse_iso8601_with_offset() {
121+
let result = parse_time("2024-01-15T10:30:00-05:00").unwrap();
122+
assert_eq!(result.to_rfc3339(), "2024-01-15T15:30:00+00:00");
123+
}
124+
125+
#[test]
126+
fn test_parse_invalid() {
127+
assert!(parse_time("invalid").is_err());
128+
assert!(parse_time("").is_err());
129+
assert!(parse_time("abc123").is_err());
130+
}
131+
132+
#[test]
133+
fn test_parse_whitespace_trimmed() {
134+
let result = parse_time(" 30m ").unwrap();
135+
let expected = Utc::now() - Duration::minutes(30);
136+
assert!((result - expected).num_seconds().abs() < 2);
137+
}
138+
}

0 commit comments

Comments
 (0)