Package codes.grow.packages.betterstack
Class BetterStackQuery
java.lang.Object
codes.grow.packages.betterstack.BetterStackQuery
- All Implemented Interfaces:
LogQueryClient
SQL query client for Better Stack Logs: the ClickHouse HTTP interface of the query host with the
connection's own Basic credentials. Get it from
BetterStackClient.query(); it is
thread-safe. Better Stack allows 4 concurrent log queries per account.
Implements LogQueryClient over the configured source table: search runs searchLogs(codes.grow.packages.betterstack.SearchLogsOptions), tail polls searchLogs, listStreams returns the configured
collection and listLabels is unsupported (Better Stack events have no labels).
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intstatic final DurationWindow of a search without a start: 24 h before the end (or before now).static final intLargest page size. -
Method Summary
Modifier and TypeMethodDescriptionstatic StringescapeParamValue(String value) Escapes aparam_<name>value for ClickHouse, which parses query parameter values in the escaped (TabSeparated) text format: backslash becomes\\, tab\t, newline\nand carriage return\r(DECISIONS 12).static StringFormats an instant as ClickHouseDateTime64(6)text in UTC (YYYY-MM-DD HH:MM:SS.ffffff).static StringjsonEscape(String text) Escapes text like a JSON string value without the surrounding quotes (quote, backslash and control characters), as it appears inside the raw event JSON.Better Stack events are schemaless JSON without labels.The configured collections:[sourceTable], or empty.static LogRecordlogRecordFromRow(Map<String, ?> row) Normalizes a{dt, raw}row into aLogRecord:body=message(elsemsg, else the raw text); severity fromseverity_number, elselevel/severitytext (default INFO), with the canonical text when the level is known; timestamp fromdt(else the event'sdt); trace ids fromspan.trace_id/span.span_id(else top-leveltrace_id/span_id, hex only);resourcefromresource; every other key plus theattributesobject into attributes.parseDateTime(Object value) Parses adtvalue: ClickHouseDateTime64text (2026-11-18 21:00:00.123456, UTC, 0 to 9 fraction digits), an RFC 3339 string, UNIX seconds or milliseconds, or anInstant.Parses a JSON-family response body (JSONEachRow, a JSON array of rows orFORMAT JSON) into rows.Runs SQL and returns the rows.Runs SQL with bound parameters and returns the rows.query(String sql, Map<String, ?> params, QueryOptions options) Runs SQL and returns the rows.queryAsync(String sql, Map<String, ?> params, QueryOptions options) Asynchronousquery(String, Map, QueryOptions).Runs SQL and returns the response text unchanged (anyFORMAT).queryRaw(String sql, Map<String, ?> params, QueryOptions options) Runs SQL with bound parameters and returns the response text unchanged.queryRawAsync(String sql, Map<String, ?> params, QueryOptions options) AsynchronousqueryRaw(String, Map, QueryOptions).renderSearchSql(SearchLogsOptions options) Renders the SQL ofsearchLogs(codes.grow.packages.betterstack.SearchLogsOptions): hotremote(<source>_logs)UNION ALL colds3Cluster(primary, <source>_s3) WHERE _row_type = 1, the inclusivedtwindow (toDateTime64('…', 6, 'UTC')),position(raw, <JSON-escaped contains>) > 0,ORDER BY dt,LIMIT <limit + 1>(to detect a next page) and the cursor'sOFFSET,FORMAT JSONEachRow.search(String query, SearchOptions options) LogQueryClient.search(java.lang.String, codes.grow.packages.betterstack.logging.SearchOptions):queryis thecontainstext, searched in the configured source table.searchAsync(String query, SearchOptions options) Asynchronoussearch(String, SearchOptions).searchLogs(SearchLogsOptions options) Searches the hot and cold logs of a collection (seerenderSearchSql(codes.grow.packages.betterstack.SearchLogsOptions)) with an inclusive time window and a literal substring match, newest first by default.searchLogsAsync(SearchLogsOptions options) AsynchronoussearchLogs(SearchLogsOptions).static StringEscapes a value as a ClickHouse single-quoted string literal (backslash, quote, newline, carriage return, tab and NUL are backslash-escaped).tail(String query, Consumer<LogRecord> onRecord, TailOptions options) PollssearchLogs(codes.grow.packages.betterstack.SearchLogsOptions)everyoptions.interval()(default 1 s) for new records of the configured source table that containquery, starting atoptions.start()(default now), and callsonRecordfor each new record indtorder.Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface codes.grow.packages.betterstack.logging.LogQueryClient
listLabelsAsync, listStreamsAsync, search, waitForLog, waitForLog, waitForLogAsync
-
Field Details
-
DEFAULT_LIMIT
public static final int DEFAULT_LIMITDefault page size ofsearchLogs(codes.grow.packages.betterstack.SearchLogsOptions)andsearch(java.lang.String, codes.grow.packages.betterstack.logging.SearchOptions).- See Also:
-
MAX_LIMIT
public static final int MAX_LIMITLargest page size.- See Also:
-
DEFAULT_SEARCH_WINDOW
Window of a search without a start: 24 h before the end (or before now).
-
-
Method Details
-
queryRaw
Runs SQL and returns the response text unchanged (anyFORMAT).- Parameters:
sql- SQL text- Returns:
- the body
-
queryRaw
Runs SQL with bound parameters and returns the response text unchanged.- Parameters:
sql- SQL with{name:Type}placeholdersparams- values: String, Number, Boolean,Instant(YYYY-MM-DD HH:MM:SS.ffffffUTC) ornull(sent as\N)options- ClickHouse settings- Returns:
- the body
- Throws:
BetterStackException- mapped by ClickHouse exception code
-
queryRawAsync
public CompletableFuture<String> queryRawAsync(String sql, Map<String, ?> params, QueryOptions options) AsynchronousqueryRaw(String, Map, QueryOptions). Parameters are bound server side: each{name:Type}placeholder takes the URL parameterparam_<name>.- Parameters:
sql- SQL with placeholdersparams- valuesoptions- ClickHouse settings- Returns:
- a future with the body
-
escapeParamValue
Escapes aparam_<name>value for ClickHouse, which parses query parameter values in the escaped (TabSeparated) text format: backslash becomes\\, tab\t, newline\nand carriage return\r(DECISIONS 12). Applied to every non-numeric parameter value byquery(String, Map).- Parameters:
value- parameter text- Returns:
- the escaped text
-
query
Runs SQL and returns the rows.- Parameters:
sql- SQL text- Returns:
- rows
-
query
Runs SQL with bound parameters and returns the rows.- Parameters:
sql- SQL with{name:Type}placeholdersparams- values (seequeryRaw(String, Map, QueryOptions))- Returns:
- rows
-
query
Runs SQL and returns the rows. Without aFORMATclauseFORMAT JSONEachRowis appended;FORMAT JSONEachRow/JSON(also withoutput_format_json_array_of_rows) are parsed, other formats raiseValidationException(usequeryRaw(java.lang.String)). ClickHouse renders 64-bit integers as strings. A ClickHouse exception appended to a200answer raises the mapped error.List<Map<String, Object>> rows = q.query( "SELECT count() AS c FROM remote(t1_app_logs) WHERE position(raw, {needle:String}) > 0", Map.of("needle", "checkout"));- Parameters:
sql- SQL with placeholdersparams- valuesoptions- ClickHouse settings- Returns:
- rows
-
queryAsync
public CompletableFuture<List<Map<String,Object>>> queryAsync(String sql, Map<String, ?> params, QueryOptions options) Asynchronousquery(String, Map, QueryOptions).- Parameters:
sql- SQL with placeholdersparams- valuesoptions- ClickHouse settings- Returns:
- a future with the rows
-
parseRows
Parses a JSON-family response body (JSONEachRow, a JSON array of rows orFORMAT JSON) into rows.- Parameters:
text- response body- Returns:
- rows
- Throws:
BetterStackException- for a ClickHouse exception in the body or invalid JSON
-
sqlString
Escapes a value as a ClickHouse single-quoted string literal (backslash, quote, newline, carriage return, tab and NUL are backslash-escaped).- Parameters:
value- text- Returns:
- the literal including quotes
-
jsonEscape
Escapes text like a JSON string value without the surrounding quotes (quote, backslash and control characters), as it appears inside the raw event JSON.- Parameters:
text- text- Returns:
- escaped text
-
formatDateTime64
Formats an instant as ClickHouseDateTime64(6)text in UTC (YYYY-MM-DD HH:MM:SS.ffffff).- Parameters:
t- instant- Returns:
- the text
-
parseDateTime
Parses adtvalue: ClickHouseDateTime64text (2026-11-18 21:00:00.123456, UTC, 0 to 9 fraction digits), an RFC 3339 string, UNIX seconds or milliseconds, or anInstant.- Parameters:
value- value- Returns:
- the instant, or empty when unparseable
-
logRecordFromRow
Normalizes a{dt, raw}row into aLogRecord:body=message(elsemsg, else the raw text); severity fromseverity_number, elselevel/severitytext (default INFO), with the canonical text when the level is known; timestamp fromdt(else the event'sdt); trace ids fromspan.trace_id/span.span_id(else top-leveltrace_id/span_id, hex only);resourcefromresource; every other key plus theattributesobject into attributes.- Parameters:
row- result row- Returns:
- the record
-
renderSearchSql
Renders the SQL ofsearchLogs(codes.grow.packages.betterstack.SearchLogsOptions): hotremote(<source>_logs)UNION ALL colds3Cluster(primary, <source>_s3) WHERE _row_type = 1, the inclusivedtwindow (toDateTime64('…', 6, 'UTC')),position(raw, <JSON-escaped contains>) > 0,ORDER BY dt,LIMIT <limit + 1>(to detect a next page) and the cursor'sOFFSET,FORMAT JSONEachRow. Values are escaped string literals; the source is a checked identifier.- Parameters:
options- search options- Returns:
- the SQL
- Throws:
ConfigException- without a source and a configured source tableValidationException- for an invalid source, limit, window or cursor
-
searchLogs
Searches the hot and cold logs of a collection (seerenderSearchSql(codes.grow.packages.betterstack.SearchLogsOptions)) with an inclusive time window and a literal substring match, newest first by default. Rows are normalized (logRecordFromRow(java.util.Map<java.lang.String, ?>)) and de-duplicated on(dt, raw)where hot and cold overlap;nextCursoris set when more rows exist.- Parameters:
options- search options- Returns:
- one page
-
searchLogsAsync
AsynchronoussearchLogs(SearchLogsOptions).- Parameters:
options- search options- Returns:
- a future page
-
search
LogQueryClient.search(java.lang.String, codes.grow.packages.betterstack.logging.SearchOptions):queryis thecontainstext, searched in the configured source table.- Specified by:
searchin interfaceLogQueryClient- Parameters:
query- textoptions- window, limit, order, cursor- Returns:
- one page
-
searchAsync
Asynchronoussearch(String, SearchOptions).- Specified by:
searchAsyncin interfaceLogQueryClient- Parameters:
query- textoptions- options- Returns:
- a future page
-
listStreams
The configured collections:[sourceTable], or empty. Better Stack's data plane has no listing endpoint.- Specified by:
listStreamsin interfaceLogQueryClient- Returns:
- collection names
-
listLabels
Better Stack events are schemaless JSON without labels.- Specified by:
listLabelsin interfaceLogQueryClient- Returns:
- never
- Throws:
UnsupportedException- always
-
tail
PollssearchLogs(codes.grow.packages.betterstack.SearchLogsOptions)everyoptions.interval()(default 1 s) for new records of the configured source table that containquery, starting atoptions.start()(default now), and callsonRecordfor each new record indtorder. Records are de-duplicated at the polling boundary; polling errors go tooptions.onError()and the next poll retries. The tail ends when the handle is stopped or the client is closed.- Specified by:
tailin interfaceLogQueryClient- Parameters:
query- text to matchonRecord- callback per record (exceptions are ignored)options- start, interval, error callback- Returns:
- the handle
- Throws:
ConfigException- without a configured source table
-