SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
Logs UI (#1436)
Pranshu Chittora7a4750a882e6
diff --git a/frontend/package.json b/frontend/package.jsonindex 9dae2b906d..f8c4aea371 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -56,7 +56,9 @@"d3-tip": "^0.9.1","dayjs": "^1.10.7","dotenv": "8.2.0",+ "eventsource": "^2.0.2","file-loader": "6.1.1",+ "flat": "^5.0.2","history": "4.10.1","html-webpack-plugin": "5.1.0","i18next": "^21.6.12",diff --git a/frontend/src/AppRoutes/pageComponents.ts b/frontend/src/AppRoutes/pageComponents.tsindex 071b5d77fa..46cf8ec34a 100644--- a/frontend/src/AppRoutes/pageComponents.ts+++ b/frontend/src/AppRoutes/pageComponents.ts@@ -100,6 +100,10 @@ export const MySettings = Loadable(() => import(/* webpackChunkName: "All MySettings" */ 'pages/MySettings'),);+export const Logs = Loadable(+ () => import(/* webpackChunkName: "Logs" */ 'pages/Logs'),+);+export const Login = Loadable(() => import(/* webpackChunkName: "Login" */ 'pages/Login'),);diff --git a/frontend/src/AppRoutes/routes.ts b/frontend/src/AppRoutes/routes.tsindex 5958d93b11..876ece4af1 100644--- a/frontend/src/AppRoutes/routes.ts+++ b/frontend/src/AppRoutes/routes.ts@@ -14,6 +14,7 @@ import {InstrumentationPage,ListAllALertsPage,Login,+ Logs,MySettings,NewDashboardPage,OrganizationSettings,@@ -193,6 +194,13 @@ const routes: AppRoutes[] = [isPrivate: true,key: 'MY_SETTINGS',},+ {+ path: ROUTES.LOGS,+ exact: true,+ component: Logs,+ key: 'LOGS',+ isPrivate: true,+ },{path: ROUTES.LOGIN,exact: true,diff --git a/frontend/src/api/logs/AddToSelectedField.ts b/frontend/src/api/logs/AddToSelectedField.tsnew file mode 100644index 0000000000..55be186f5b--- /dev/null+++ b/frontend/src/api/logs/AddToSelectedField.ts@@ -0,0 +1,23 @@+import axios from 'api';+import { ErrorResponseHandler } from 'api/ErrorResponseHandler';+import { AxiosError } from 'axios';+import { ErrorResponse, SuccessResponse } from 'types/api';+import { PayloadProps, Props } from 'types/api/logs/addToSelectedFields';++const AddToSelectedFields = async (+ props: Props,+): Promise<SuccessResponse<PayloadProps> | ErrorResponse> => {+ try {+ const data = await axios.post(`/logs/fields`, props);+ return {+ statusCode: 200,+ error: null,+ message: '',+ payload: data.data,+ };+ } catch (error) {+ return ErrorResponseHandler(error as AxiosError);+ }+};++export default AddToSelectedFields;diff --git a/frontend/src/api/logs/GetLogs.ts b/frontend/src/api/logs/GetLogs.tsnew file mode 100644index 0000000000..411e2e38ca--- /dev/null+++ b/frontend/src/api/logs/GetLogs.ts@@ -0,0 +1,26 @@+import axios from 'api';+import { ErrorResponseHandler } from 'api/ErrorResponseHandler';+import { AxiosError } from 'axios';+import { ErrorResponse, SuccessResponse } from 'types/api';+import { PayloadProps, Props } from 'types/api/logs/getLogs';++const GetLogs = async (+ props: Props,+): Promise<SuccessResponse<PayloadProps> | ErrorResponse> => {+ try {+ const data = await axios.get(`/logs`, {+ params: props,+ });++ return {+ statusCode: 200,+ error: null,+ message: '',+ payload: data.data.results,+ };+ } catch (error) {+ return ErrorResponseHandler(error as AxiosError);+ }+};++export default GetLogs;diff --git a/frontend/src/api/logs/GetLogsAggregate.ts b/frontend/src/api/logs/GetLogsAggregate.tsnew file mode 100644index 0000000000..3385999bb7--- /dev/null+++ b/frontend/src/api/logs/GetLogsAggregate.ts@@ -0,0 +1,26 @@+import axios from 'api';+import { ErrorResponseHandler } from 'api/ErrorResponseHandler';+import { AxiosError } from 'axios';+import { ErrorResponse, SuccessResponse } from 'types/api';+import { PayloadProps, Props } from 'types/api/logs/getLogsAggregate';++const GetLogsAggregate = async (+ props: Props,+): Promise<SuccessResponse<PayloadProps> | ErrorResponse> => {+ try {+ const data = await axios.get(`/logs/aggregate`, {+ params: props,+ });++ return {+ statusCode: 200,+ error: null,+ message: '',+ payload: data.data.items,+ };+ } catch (error) {+ return ErrorResponseHandler(error as AxiosError);+ }+};++export default GetLogsAggregate;diff --git a/frontend/src/api/logs/GetSearchFields.ts b/frontend/src/api/logs/GetSearchFields.tsnew file mode 100644index 0000000000..ce3188bf4b--- /dev/null+++ b/frontend/src/api/logs/GetSearchFields.ts@@ -0,0 +1,24 @@+import axios from 'api';+import { ErrorResponseHandler } from 'api/ErrorResponseHandler';+import { AxiosError } from 'axios';+import { ErrorResponse, SuccessResponse } from 'types/api';+import { PayloadProps } from 'types/api/logs/getSearchFields';++const GetSearchFields = async (): Promise<+ SuccessResponse<PayloadProps> | ErrorResponse+> => {+ try {+ const data = await axios.get(`/logs/fields`);++ return {+ statusCode: 200,+ error: null,+ message: '',+ payload: data.data,+ };+ } catch (error) {+ return ErrorResponseHandler(error as AxiosError);+ }+};++export default GetSearchFields;diff --git a/frontend/src/api/logs/RemoveFromSelectedField.ts b/frontend/src/api/logs/RemoveFromSelectedField.tsnew file mode 100644index 0000000000..c33ff9fca1--- /dev/null+++ b/frontend/src/api/logs/RemoveFromSelectedField.ts@@ -0,0 +1,23 @@+import axios from 'api';+import { ErrorResponseHandler } from 'api/ErrorResponseHandler';+import { AxiosError } from 'axios';+import { ErrorResponse, SuccessResponse } from 'types/api';+import { PayloadProps, Props } from 'types/api/logs/addToSelectedFields';++const RemoveSelectedField = async (+ props: Props,+): Promise<SuccessResponse<PayloadProps> | ErrorResponse> => {+ try {+ const data = await axios.post(`/logs/fields`, props);+ return {+ statusCode: 200,+ error: null,+ message: '',+ payload: data.data,+ };+ } catch (error) {+ return ErrorResponseHandler(error as AxiosError);+ }+};++export default RemoveSelectedField;diff --git a/frontend/src/api/logs/livetail.ts b/frontend/src/api/logs/livetail.tsnew file mode 100644index 0000000000..a622b09cb9--- /dev/null+++ b/frontend/src/api/logs/livetail.ts@@ -0,0 +1,18 @@+import 'eventsource/example/eventsource-polyfill';++import apiV1 from 'api/apiV1';+import getLocalStorageKey from 'api/browser/localstorage/get';+import { ENVIRONMENT } from 'constants/env';+import { LOCALSTORAGE } from 'constants/localStorage';++export const LiveTail = (queryParams) => {+ const dict = {+ headers: {+ Authorization: `Bearer ${getLocalStorageKey(LOCALSTORAGE.AUTH_TOKEN)}`,+ },+ };+ return new EventSourcePolyfill(+ `${ENVIRONMENT.baseURL}${apiV1}/logs/tail?${queryParams}`,+ dict,+ );+};diff --git a/frontend/src/components/Graph/index.tsx b/frontend/src/components/Graph/index.tsxindex 3df4de3caa..ecbb50cc02 100644--- a/frontend/src/components/Graph/index.tsx+++ b/frontend/src/components/Graph/index.tsx@@ -65,6 +65,7 @@ function Graph({yAxisUnit = 'short',forceReRender,staticLine,+ containerHeight,}: GraphProps): JSX.Element {const { isDarkMode } = useSelector<AppState, AppReducer>((state) => state.app);const chartRef = useRef<HTMLCanvasElement>(null);@@ -241,7 +242,7 @@ function Graph({}, [buildChart, forceReRender]);return (- <div style={{ height: '85%' }}>+ <div style={{ height: containerHeight }}><canvas ref={chartRef} /><LegendsContainer id={name} /></div>@@ -259,6 +260,7 @@ interface GraphProps {yAxisUnit?: string;forceReRender?: boolean | null | number;staticLine?: StaticLineProps | undefined;+ containerHeight?: string | number;}export interface StaticLineProps {@@ -285,5 +287,6 @@ Graph.defaultProps = {yAxisUnit: undefined,forceReRender: undefined,staticLine: undefined,+ containerHeight: '85%',};export default Graph;diff --git a/frontend/src/components/Logs/AddToQueryHOC.tsx b/frontend/src/components/Logs/AddToQueryHOC.tsxnew file mode 100644index 0000000000..a95583cd3c--- /dev/null+++ b/frontend/src/components/Logs/AddToQueryHOC.tsx@@ -0,0 +1,135 @@+import { Button, Popover, Tag, Tooltip } from 'antd';+import getStep from 'lib/getStep';+import { generateFilterQuery } from 'lib/logs/generateFilterQuery';+import React, { memo, useCallback, useMemo } from 'react';+import { connect, useDispatch, useSelector } from 'react-redux';+import { bindActionCreators, Dispatch } from 'redux';+import { ThunkDispatch } from 'redux-thunk';+import { getLogs } from 'store/actions/logs/getLogs';+import { getLogsAggregate } from 'store/actions/logs/getLogsAggregate';+import { AppState } from 'store/reducers';+import AppActions from 'types/actions';+import { SET_SEARCH_QUERY_STRING, TOGGLE_LIVE_TAIL } from 'types/actions/logs';+import { GlobalReducer } from 'types/reducer/globalTime';+import ILogsReducer from 'types/reducer/logs';++function AddToQueryHOC({+ fieldKey,+ fieldValue,+ children,+ getLogs,+ getLogsAggregate,+}) {+ const {+ searchFilter: { queryString },+ logLinesPerPage,+ idStart,+ idEnd,+ liveTail,+ } = useSelector<AppState, ILogsReducer>((store) => store.logs);+ const dispatch = useDispatch();++ const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(+ (state) => state.globalTime,+ );+ const generatedQuery = useMemo(+ () => generateFilterQuery({ fieldKey, fieldValue, type: 'IN' }),+ [fieldKey, fieldValue],+ );++ const handleQueryAdd = useCallback(() => {+ let updatedQueryString = queryString || '';++ if (updatedQueryString.length === 0) {+ updatedQueryString += `${generatedQuery}`;+ } else {+ updatedQueryString += ` AND ${generatedQuery}`;+ }+ dispatch({+ type: SET_SEARCH_QUERY_STRING,+ payload: updatedQueryString,+ });+ if (liveTail === 'STOPPED') {+ getLogs({+ q: updatedQueryString,+ limit: logLinesPerPage,+ orderBy: 'timestamp',+ order: 'desc',+ timestampStart: minTime,+ timestampEnd: maxTime,+ ...(idStart ? { idGt: idStart } : {}),+ ...(idEnd ? { idLt: idEnd } : {}),+ });+ getLogsAggregate({+ timestampStart: minTime,+ timestampEnd: maxTime,+ step: getStep({+ start: minTime,+ end: maxTime,+ inputFormat: 'ns',+ }),+ q: updatedQueryString,+ ...(idStart ? { idGt: idStart } : {}),+ ...(idEnd ? { idLt: idEnd } : {}),+ });+ }++ else if (liveTail === 'PLAYING') {+ dispatch({+ type: TOGGLE_LIVE_TAIL,+ payload: 'PAUSED',+ });+ setTimeout(+ () =>+ dispatch({+ type: TOGGLE_LIVE_TAIL,+ payload: liveTail,+ }),+ 0,+ );+ }+ }, [+ dispatch,+ generatedQuery,+ getLogs,+ idEnd,+ idStart,+ logLinesPerPage,+ maxTime,+ minTime,+ queryString,+ ]);++ const popOverContent = (+ <span style={{ fontSize: '0.9rem' }}>Add to query: {fieldKey}</span>+ );+ return (+ <Button+ size="small"+ type="text"+ style={{+ margin: 0,+ padding: 0,+ }}+ onClick={handleQueryAdd}+ >+ <Popover placement="top" content={popOverContent}>+ {children}+ </Popover>+ </Button>+ );+}++interface DispatchProps {+ getLogs: () => (dispatch: Dispatch<AppActions>) => void;+ getLogsAggregate: () => (dispatch: Dispatch<AppActions>) => void;+}++const mapDispatchToProps = (+ dispatch: ThunkDispatch<unknown, unknown, AppActions>,+): DispatchProps => ({+ getLogs: bindActionCreators(getLogs, dispatch),+ getLogsAggregate: bindActionCreators(getLogsAggregate, dispatch),+});++export default connect(null, mapDispatchToProps)(memo(AddToQueryHOC));diff --git a/frontend/src/components/Logs/CategoryHeading/index.tsx b/frontend/src/components/Logs/CategoryHeading/index.tsxnew file mode 100644index 0000000000..f48160593a--- /dev/null+++ b/frontend/src/components/Logs/CategoryHeading/index.tsx@@ -0,0 +1,12 @@+import React from 'react';++import { CategoryHeadingText } from './styles';++interface ICategoryHeadingProps {+ children: React.ReactNode;+}+function CategoryHeading({ children }: ICategoryHeadingProps): JSX.Element {+ return <CategoryHeadingText type="secondary">{children}</CategoryHeadingText>;+}++export default CategoryHeading;diff --git a/frontend/src/components/Logs/CategoryHeading/styles.ts b/frontend/src/components/Logs/CategoryHeading/styles.tsnew file mode 100644index 0000000000..99278700dd--- /dev/null+++ b/frontend/src/components/Logs/CategoryHeading/styles.ts@@ -0,0 +1,6 @@+import { Typography } from 'antd';+import styled from 'styled-components';++export const CategoryHeadingText = styled(Typography.Text)`+ font-size: 0.8rem;+`;diff --git a/frontend/src/components/Logs/CopyClipboardHOC.tsx b/frontend/src/components/Logs/CopyClipboardHOC.tsxnew file mode 100644index 0000000000..f1f2a0f9b6--- /dev/null+++ b/frontend/src/components/Logs/CopyClipboardHOC.tsx@@ -0,0 +1,28 @@+import { Button, Popover, Tooltip } from 'antd';+import React from 'react';+import { useCopyToClipboard } from 'react-use';++function CopyClipboardHOC({ textToCopy, children }) {+ const [_state, setCopy] = useCopyToClipboard();++ return (+ <span+ style={{+ margin: 0,+ padding: 0,+ cursor: 'pointer'+ }}+ onClick={() => setCopy(textToCopy)}+ role="button"+ >+ <Popover+ placement="top"+ content={<span style={{ fontSize: '0.9rem' }}>Copy to clipboard</span>}+ >+ {children}+ </Popover>+ </span>+ );+}++export default CopyClipboardHOC;diff --git a/frontend/src/components/Logs/LogItem/index.tsx b/frontend/src/components/Logs/LogItem/index.tsxnew file mode 100644index 0000000000..5ddf160097--- /dev/null+++ b/frontend/src/components/Logs/LogItem/index.tsx@@ -0,0 +1,140 @@+import { blue, grey, orange } from '@ant-design/colors';+import { CopyFilled, CopyrightCircleFilled, ExpandAltOutlined } from '@ant-design/icons';+import { Button, Card, Divider, Row, Typography } from 'antd';+import { map } from 'd3';+import { FlatLogData } from 'lib/logs/flatLogData';+import { flatMap, flatMapDeep } from 'lodash-es';+import React, { useCallback, useMemo } from 'react';+import { useDispatch, useSelector } from 'react-redux';+import { useCopyToClipboard } from 'react-use';+import { AppState } from 'store/reducers';+import { SET_DETAILED_LOG_DATA } from 'types/actions/logs';+import ILogsReducer from 'types/reducer/logs';++import AddToQueryHOC from '../AddToQueryHOC';+import CopyClipboardHOC from '../CopyClipboardHOC';+import { Container } from './styles';++function LogGeneralField({ fieldKey, fieldValue }) {+ return (+ <div+ style={{+ display: 'flex',+ overflow: 'hidden',+ width: '100%',+ }}+ >+ <Typography.Text type="secondary">{fieldKey}</Typography.Text>+ <CopyClipboardHOC textToCopy={fieldValue}>+ <Typography.Text ellipsis>+ {': '}+ {fieldValue}+ </Typography.Text>+ </CopyClipboardHOC>+ </div>+ );+}++function LogSelectedField({ fieldKey = '', fieldValue = '' }) {+ return (+ <div+ style={{+ display: 'flex',+ overflow: 'hidden',+ width: '100%',+ }}+ >+ <AddToQueryHOC fieldKey={fieldKey} fieldValue={fieldValue}>+ <Typography.Text>+ {`"`}+ <span style={{ color: blue[4] }}>{fieldKey}</span>+ {`"`}+ </Typography.Text>+ </AddToQueryHOC>+ <CopyClipboardHOC textToCopy={fieldValue}>+ <Typography.Text ellipsis>+ <span>+ {': '}+ {typeof fieldValue === 'string' && `"`}+ </span>+ <span style={{ color: orange[6] }}>{fieldValue}</span>+ {typeof fieldValue === 'string' && `"`}+ </Typography.Text>+ </CopyClipboardHOC>+ </div>+ );+}++function LogItem({ logData }) {+ const {+ fields: { selected },+ } = useSelector<AppState, ILogsReducer>((state) => state.logs);+ const dispatch = useDispatch();+ const flattenLogData = useMemo(() => FlatLogData(logData), [logData]);+ const [_state, setCopy] = useCopyToClipboard();++ const handleDetailedView = useCallback(() => {+ dispatch({+ type: SET_DETAILED_LOG_DATA,+ payload: logData,+ });+ }, [dispatch, logData]);++ const handleCopyJSON = () => {+ setCopy(JSON.stringify(logData, null, 2))+ }+ return (+ <Container>+ <div style={{ maxWidth: '100%' }}>+ <div>+ {'{'}+ <div style={{ marginLeft: '0.5rem' }}>+ <LogGeneralField fieldKey="log" fieldValue={flattenLogData.body} />+ {flattenLogData.stream && (+ <LogGeneralField fieldKey="stream" fieldValue={flattenLogData.stream} />+ )}+ <LogGeneralField+ fieldKey="timestamp"+ fieldValue={flattenLogData.timestamp}+ />+ </div>+ {'}'}+ </div>+ <div>+ {map(selected, (field) => {+ return flattenLogData[field.name] ? (+ <LogSelectedField+ key={field.name}+ fieldKey={field.name}+ fieldValue={flattenLogData[field.name]}+ />+ ) : null;+ })}+ </div>+ </div>+ <Divider style={{ padding: 0, margin: '0.4rem 0', opacity: 0.5 }} />+ <Row>+ <Button+ size="small"+ type="text"+ onClick={handleDetailedView}+ style={{ color: blue[5], padding: 0, margin: 0 }}+ >+ {' '}+ <ExpandAltOutlined /> View Details+ </Button>+ <Button+ size="small"+ type="text"+ onClick={handleCopyJSON}+ style={{ padding: 0, margin: 0, color: grey[1] }}+ >+ {' '}+ <CopyFilled /> Copy JSON+ </Button>+ </Row>+ </Container>+ );+}++export default LogItem;diff --git a/frontend/src/components/Logs/LogItem/styles.ts b/frontend/src/components/Logs/LogItem/styles.tsnew file mode 100644index 0000000000..cb2ce15e27--- /dev/null+++ b/frontend/src/components/Logs/LogItem/styles.ts@@ -0,0 +1,18 @@+import { Card } from 'antd';+import styled, { keyframes } from 'styled-components';++const fadeInAnimation = keyframes`+ 0% { opacity: 0; }+ 100% { opacity: 1;}+`;++export const Container = styled(Card)`+ width: 100% !important;+ margin-bottom: 0.3rem;+ .ant-card-body {+ padding: 0.3rem 0.6rem;+ }+ animation-name: ${fadeInAnimation};+ animation-duration: 0.2s;+ animation-timing-function: ease-in;+`;diff --git a/frontend/src/constants/routes.ts b/frontend/src/constants/routes.tsindex 506474af97..c9fc9fe90a 100644--- a/frontend/src/constants/routes.ts+++ b/frontend/src/constants/routes.ts@@ -26,6 +26,7 @@ const ROUTES = {SOMETHING_WENT_WRONG: '/something-went-wrong',UN_AUTHORIZED: '/un-authorized',NOT_FOUND: '/not-found',+ LOGS: '/logs',HOME_PAGE: '/',PASSWORD_RESET: '/password-reset',};diff --git a/frontend/src/container/GeneralSettings/GeneralSettings.tsx b/frontend/src/container/GeneralSettings/GeneralSettings.tsxindex 0f950ec05b..69b49b9e53 100644--- a/frontend/src/container/GeneralSettings/GeneralSettings.tsx+++ b/frontend/src/container/GeneralSettings/GeneralSettings.tsx@@ -1,6 +1,7 @@import { LoadingOutlined } from '@ant-design/icons';import {Button,+ Card,Col,Divider,Modal,@@ -26,6 +27,7 @@ import {} from 'types/api/disks/getDisks';import { TTTLType } from 'types/api/settings/common';import {+ PayloadPropsLogs as GetRetentionPeriodLogsPayload,PayloadPropsMetrics as GetRetentionPeriodMetricsPayload,PayloadPropsTraces as GetRetentionPeriodTracesPayload,} from 'types/api/settings/getRetention';@@ -40,19 +42,25 @@ type NumberOrNull = number | null;function GeneralSettings({metricsTtlValuesPayload,tracesTtlValuesPayload,+ logsTtlValuesPayload,getAvailableDiskPayload,metricsTtlValuesRefetch,tracesTtlValuesRefetch,+ logsTtlValuesRefetch,}: GeneralSettingsProps): JSX.Element {const { t } = useTranslation(['generalSettings']);const [modalMetrics, setModalMetrics] = useState<boolean>(false);+ const [modalTraces, setModalTraces] = useState<boolean>(false);+ const [modalLogs, setModalLogs] = useState<boolean>(false);+const [postApiLoadingMetrics, setPostApiLoadingMetrics] = useState<boolean>(false,);const [postApiLoadingTraces, setPostApiLoadingTraces] = useState<boolean>(false,);- const [modalTraces, setModalTraces] = useState<boolean>(false);+ const [postApiLoadingLogs, setPostApiLoadingLogs] = useState<boolean>(false);+const [availableDisks] = useState<IDiskType[]>(getAvailableDiskPayload);const [metricsCurrentTTLValues, setMetricsCurrentTTLValues] = useState(@@ -62,6 +70,10 @@ function GeneralSettings({tracesTtlValuesPayload,);+ const [logsCurrentTTLValues, setLogsCurrentTTLValues] = useState(+ logsTtlValuesPayload,+ );+const { role } = useSelector<AppState, AppReducer>((state) => state.app);const [setRetentionPermission] = useComponentPermission(@@ -86,6 +98,15 @@ function GeneralSettings({setTracesS3RetentionPeriod,] = useState<NumberOrNull>(null);+ const [+ logsTotalRetentionPeriod,+ setLogsTotalRetentionPeriod,+ ] = useState<NumberOrNull>(null);+ const [+ logsS3RetentionPeriod,+ setLogsS3RetentionPeriod,+ ] = useState<NumberOrNull>(null);+useEffect(() => {if (metricsCurrentTTLValues) {setMetricsTotalRetentionPeriod(@@ -112,6 +133,17 @@ function GeneralSettings({}}, [tracesCurrentTTLValues]);+ useEffect(() => {+ if (logsCurrentTTLValues) {+ setLogsTotalRetentionPeriod(logsCurrentTTLValues.logs_ttl_duration_hrs);+ setLogsS3RetentionPeriod(+ logsCurrentTTLValues.logs_move_ttl_duration_hrs+ ? logsCurrentTTLValues.logs_move_ttl_duration_hrs+ : null,+ );+ }+ }, [logsCurrentTTLValues]);+useInterval(async (): Promise<void> => {if (metricsTtlValuesPayload.status === 'pending') {@@ -130,13 +162,24 @@ function GeneralSettings({tracesTtlValuesPayload.status === 'pending' ? 1000 : null,);+ useInterval(+ async (): Promise<void> => {+ if (logsTtlValuesPayload.status === 'pending') {+ logsTtlValuesRefetch();+ }+ },+ logsTtlValuesPayload.status === 'pending' ? 1000 : null,+ );+const onModalToggleHandler = (type: TTTLType): void => {if (type === 'metrics') setModalMetrics((modal) => !modal);if (type === 'traces') setModalTraces((modal) => !modal);+ if (type === 'logs') setModalLogs((modal) => !modal);};const onPostApiLoadingHandler = (type: TTTLType): void => {if (type === 'metrics') setPostApiLoadingMetrics((modal) => !modal);if (type === 'traces') setPostApiLoadingTraces((modal) => !modal);+ if (type === 'logs') setPostApiLoadingLogs((modal) => !modal);};const onClickSaveHandler = useCallback(@@ -157,7 +200,13 @@ function GeneralSettings({[availableDisks],);- const [isMetricsSaveDisabled, isTracesSaveDisabled, errorText] = useMemo((): [+ const [+ isMetricsSaveDisabled,+ isTracesSaveDisabled,+ isLogsSaveDisabled,+ errorText,+ ] = useMemo((): [+ boolean,boolean,boolean,string,@@ -174,6 +223,7 @@ function GeneralSettings({// Defaults to button not disabled and empty error message text.let isMetricsSaveDisabled = false;let isTracesSaveDisabled = false;+ let isLogsSaveDisabled = false;let errorText = '';if (s3Enabled) {@@ -189,18 +239,35 @@ function GeneralSettings({) {isTracesSaveDisabled = true;errorText = messages.compareError('traces');+ } else if (+ (logsTotalRetentionPeriod || logsS3RetentionPeriod) &&+ Number(logsTotalRetentionPeriod) <= Number(logsS3RetentionPeriod)+ ) {+ isLogsSaveDisabled = true;+ errorText = messages.compareError('logs');}}- if (!metricsTotalRetentionPeriod || !tracesTotalRetentionPeriod) {+ if (+ !metricsTotalRetentionPeriod ||+ !tracesTotalRetentionPeriod ||+ !logsTotalRetentionPeriod+ ) {isMetricsSaveDisabled = true;isTracesSaveDisabled = true;- if (!metricsTotalRetentionPeriod && !tracesTotalRetentionPeriod) {- errorText = messages.nullValueError('metrics and traces');+ isLogsSaveDisabled = true;+ if (+ !metricsTotalRetentionPeriod &&+ !tracesTotalRetentionPeriod &&+ !logsTotalRetentionPeriod+ ) {+ errorText = messages.nullValueError('metrics, traces and logs');} else if (!metricsTotalRetentionPeriod) {errorText = messages.nullValueError('metrics');} else if (!tracesTotalRetentionPeriod) {errorText = messages.nullValueError('traces');+ } else if (!logsTotalRetentionPeriod) {+ errorText = messages.nullValueError('logs');}}if (@@ -219,8 +286,23 @@ function GeneralSettings({)isTracesSaveDisabled = true;- return [isMetricsSaveDisabled, isTracesSaveDisabled, errorText];+ if (+ logsCurrentTTLValues.logs_ttl_duration_hrs === logsTotalRetentionPeriod &&+ logsCurrentTTLValues.logs_move_ttl_duration_hrs === logsS3RetentionPeriod+ )+ isLogsSaveDisabled = true;++ return [+ isMetricsSaveDisabled,+ isTracesSaveDisabled,+ isLogsSaveDisabled,+ errorText,+ ];}, [+ logsCurrentTTLValues.logs_move_ttl_duration_hrs,+ logsCurrentTTLValues.logs_ttl_duration_hrs,+ logsS3RetentionPeriod,+ logsTotalRetentionPeriod,metricsCurrentTTLValues.metrics_move_ttl_duration_hrs,metricsCurrentTTLValues?.metrics_ttl_duration_hrs,metricsS3RetentionPeriod,@@ -235,21 +317,36 @@ function GeneralSettings({// eslint-disable-next-line sonarjs/cognitive-complexityconst onOkHandler = async (type: TTTLType): Promise<void> => {+ let apiCallTotalRetention;+ let apiCallS3Retention;++ switch (type) {+ case 'metrics': {+ apiCallTotalRetention = metricsTotalRetentionPeriod;+ apiCallS3Retention = metricsS3RetentionPeriod;+ break;+ }+ case 'traces': {+ apiCallTotalRetention = tracesTotalRetentionPeriod;+ apiCallS3Retention = tracesS3RetentionPeriod;+ break;+ }+ case 'logs': {+ apiCallTotalRetention = logsTotalRetentionPeriod;+ apiCallS3Retention = logsS3RetentionPeriod;+ break;+ }+ default: {+ break;+ }+ }try {onPostApiLoadingHandler(type);const setTTLResponse = await setRetentionApi({type,- totalDuration: `${- (type === 'metrics'- ? metricsTotalRetentionPeriod- : tracesTotalRetentionPeriod) || -1- }h`,+ totalDuration: `${apiCallTotalRetention || -1}h`,coldStorage: s3Enabled ? 's3' : null,- toColdDuration: `${- (type === 'metrics'- ? metricsS3RetentionPeriod- : tracesS3RetentionPeriod) || -1- }h`,+ toColdDuration: `${apiCallS3Retention || -1}h`,});let hasSetTTLFailed = false;if (setTTLResponse.statusCode === 409) {@@ -281,6 +378,15 @@ function GeneralSettings({traces_move_ttl_duration_hrs: tracesS3RetentionPeriod || -1,status: '',});+ } else if (type === 'logs') {+ logsTtlValuesRefetch();+ if (!hasSetTTLFailed)+ // Updates the currentTTL Values in order to avoid pushing the same values.+ setLogsCurrentTTLValues({+ logs_ttl_duration_hrs: logsTotalRetentionPeriod || -1,+ logs_move_ttl_duration_hrs: logsS3RetentionPeriod || -1,+ status: '',+ });}} catch (error) {notification.error({@@ -375,63 +481,107 @@ function GeneralSettings({/>),},- ].map((category, idx, renderArr): JSX.Element | null => {+ {+ name: 'Logs',+ retentionFields: [+ {+ name: t('total_retention_period'),+ value: logsTotalRetentionPeriod,+ setValue: setLogsTotalRetentionPeriod,+ },+ {+ name: t('move_to_s3'),+ value: logsS3RetentionPeriod,+ setValue: setLogsS3RetentionPeriod,+ hide: !s3Enabled,+ },+ ],+ save: {+ modal: modalLogs,+ modalOpen: (): void => onClickSaveHandler('logs'),+ apiLoading: postApiLoadingLogs,+ saveButtonText:+ logsTtlValuesPayload.status === 'pending' ? (+ <span>+ <Spin spinning size="small" indicator={<LoadingOutlined spin />} />{' '}+ {t('retention_save_button.pending', { name: 'logs' })}+ </span>+ ) : (+ <span>{t('retention_save_button.success')}</span>+ ),+ isDisabled: logsTtlValuesPayload.status === 'pending' || isLogsSaveDisabled,+ },+ statusComponent: (+ <StatusMessage+ total_retention={logsTtlValuesPayload.expected_logs_ttl_duration_hrs}+ status={logsTtlValuesPayload.status}+ s3_retention={logsTtlValuesPayload.expected_logs_move_ttl_duration_hrs}+ />+ ),+ },+ ].map((category): JSX.Element | null => {if (Array.isArray(category.retentionFields) &&category.retentionFields.length > 0) {return (<React.Fragment key={category.name}>- <Col xs={22} xl={11} key={category.name}>- <Typography.Title level={3}>{category.name}</Typography.Title>-- {category.retentionFields.map((retentionField) => (- <Retention- key={retentionField.name}- text={retentionField.name}- retentionValue={retentionField.value}- setRetentionValue={retentionField.setValue}- hide={!!retentionField.hide}+ <Col xs={22} xl={11} key={category.name} style={{ margin: '0.5rem' }}>+ <Card style={{ height: '100%', minHeight: 300 }}>+ <Typography.Title style={{ margin: 0 }} level={3}>+ {category.name}+ </Typography.Title>+ <Divider+ style={{+ margin: '0.5rem 0',+ padding: 0,+ opacity: 0.5,+ marginBottom: '1rem',+ }}/>- ))}- <ActionItemsContainer>- <Button- type="primary"- onClick={category.save.modalOpen}- disabled={category.save.isDisabled}+ {category.retentionFields.map((retentionField) => (+ <Retention+ key={retentionField.name}+ text={retentionField.name}+ retentionValue={retentionField.value}+ setRetentionValue={retentionField.setValue}+ hide={!!retentionField.hide}+ />+ ))}+ <ActionItemsContainer>+ <Button+ type="primary"+ onClick={category.save.modalOpen}+ disabled={category.save.isDisabled}+ >+ {category.save.saveButtonText}+ </Button>+ {category.statusComponent}+ </ActionItemsContainer>+ <Modal+ title={t('retention_confirmation')}+ focusTriggerAfterClose+ forceRender+ destroyOnClose+ closable+ onCancel={(): void =>+ onModalToggleHandler(category.name.toLowerCase() as TTTLType)+ }+ onOk={(): Promise<void> =>+ onOkHandler(category.name.toLowerCase() as TTTLType)+ }+ centered+ visible={category.save.modal}+ confirmLoading={category.save.apiLoading}>- {category.save.saveButtonText}- </Button>- {category.statusComponent}- </ActionItemsContainer>- <Modal- title={t('retention_confirmation')}- focusTriggerAfterClose- forceRender- destroyOnClose- closable- onCancel={(): void =>- onModalToggleHandler(category.name.toLowerCase() as TTTLType)- }- onOk={(): Promise<void> =>- onOkHandler(category.name.toLowerCase() as TTTLType)- }- centered- visible={category.save.modal}- confirmLoading={category.save.apiLoading}- >- <Typography>- {t('retention_confirmation_description', {- name: category.name.toLowerCase(),- })}- </Typography>- </Modal>+ <Typography>+ {t('retention_confirmation_description', {+ name: category.name.toLowerCase(),+ })}+ </Typography>+ </Modal>+ </Card></Col>- {idx < renderArr.length && (- <Col xs={0} xl={1} style={{ textAlign: 'center' }}>- <Divider type="vertical" dashed style={{ height: '100%' }} />- </Col>- )}</React.Fragment>);}@@ -451,7 +601,7 @@ function GeneralSettings({{errorText && <ErrorText>{errorText}</ErrorText>}</ErrorTextContainer>- <Row justify="space-around">{renderConfig}</Row>+ <Row justify="start">{renderConfig}</Row></Col>);}@@ -460,12 +610,16 @@ interface GeneralSettingsProps {getAvailableDiskPayload: GetDisksPayload;metricsTtlValuesPayload: GetRetentionPeriodMetricsPayload;tracesTtlValuesPayload: GetRetentionPeriodTracesPayload;+ logsTtlValuesPayload: GetRetentionPeriodLogsPayload;metricsTtlValuesRefetch: UseQueryResult<ErrorResponse | SuccessResponse<GetRetentionPeriodMetricsPayload>>['refetch'];tracesTtlValuesRefetch: UseQueryResult<ErrorResponse | SuccessResponse<GetRetentionPeriodTracesPayload>>['refetch'];+ logsTtlValuesRefetch: UseQueryResult<+ ErrorResponse | SuccessResponse<GetRetentionPeriodLogsPayload>+ >['refetch'];}export default GeneralSettings;diff --git a/frontend/src/container/GeneralSettings/Retention.tsx b/frontend/src/container/GeneralSettings/Retention.tsxindex 54fb89a394..00b7ff7f9f 100644--- a/frontend/src/container/GeneralSettings/Retention.tsx+++ b/frontend/src/container/GeneralSettings/Retention.tsx@@ -84,10 +84,10 @@ function Retention({return (<RetentionContainer><Row justify="space-between">- <Col flex={1} style={{ display: 'flex' }}>+ <Col span={12} style={{ display: 'flex' }}><RetentionFieldLabel>{text}</RetentionFieldLabel></Col>- <Col flex="150px">+ <Row span={12} justify="end"><RetentionFieldInputContainer><Inputvalue={selectedValue && selectedValue >= 0 ? selectedValue : ''}@@ -102,7 +102,7 @@ function Retention({{menuItems}</Select></RetentionFieldInputContainer>- </Col>+ </Row></Row></RetentionContainer>);diff --git a/frontend/src/container/GeneralSettings/index.tsx b/frontend/src/container/GeneralSettings/index.tsxindex 2c66042500..2e803563e4 100644--- a/frontend/src/container/GeneralSettings/index.tsx+++ b/frontend/src/container/GeneralSettings/index.tsx@@ -21,6 +21,7 @@ function GeneralSettings(): JSX.Element {const [getRetentionPeriodMetricsApiResponse,getRetentionPeriodTracesApiResponse,+ getRetentionPeriodLogsApiResponse,getDisksResponse,] = useQueries([{@@ -33,6 +34,10 @@ function GeneralSettings(): JSX.Element {getRetentionPeriodApi('traces'),queryKey: 'getRetentionPeriodApiTraces',},+ {+ queryFn: (): TRetentionAPIReturn<'logs'> => getRetentionPeriodApi('logs'),+ queryKey: 'getRetentionPeriodApiLogs',+ },{queryFn: getDisks,queryKey: 'getDisks',@@ -60,17 +65,27 @@ function GeneralSettings(): JSX.Element {</Typography>);}+ // Error State - When RetentionPeriodLogsApi or getDiskApi gets errored out.+ if (getRetentionPeriodLogsApiResponse.isError || getDisksResponse.isError) {+ return (+ <Typography>+ {getRetentionPeriodLogsApiResponse.data?.error ||+ getDisksResponse.data?.error ||+ t('something_went_wrong')}+ </Typography>+ );+ }// Loading State - When Metrics, Traces and Disk API are in progress and the promise has not been resolved/reject.if (- getRetentionPeriodMetricsApiResponse.isLoading ||getDisksResponse.isLoading ||!getDisksResponse.data?.payload ||+ getRetentionPeriodMetricsApiResponse.isLoading ||!getRetentionPeriodMetricsApiResponse.data?.payload ||getRetentionPeriodTracesApiResponse.isLoading ||- getDisksResponse.isLoading ||- !getDisksResponse.data?.payload ||- !getRetentionPeriodTracesApiResponse.data?.payload+ !getRetentionPeriodTracesApiResponse.data?.payload ||+ getRetentionPeriodLogsApiResponse.isLoading ||+ !getRetentionPeriodLogsApiResponse.data?.payload) {return <Spinner tip="Loading.." height="70vh" />;}@@ -83,6 +98,8 @@ function GeneralSettings(): JSX.Element {metricsTtlValuesRefetch: getRetentionPeriodMetricsApiResponse.refetch,tracesTtlValuesPayload: getRetentionPeriodTracesApiResponse.data?.payload,tracesTtlValuesRefetch: getRetentionPeriodTracesApiResponse.refetch,+ logsTtlValuesPayload: getRetentionPeriodLogsApiResponse.data?.payload,+ logsTtlValuesRefetch: getRetentionPeriodLogsApiResponse.refetch,}}/>);diff --git a/frontend/src/container/LogControls/index.tsx b/frontend/src/container/LogControls/index.tsxnew file mode 100644index 0000000000..cd38b796ad--- /dev/null+++ b/frontend/src/container/LogControls/index.tsx@@ -0,0 +1,117 @@+import {+ ArrowLeftOutlined,+ FastBackwardOutlined,+ LeftOutlined,+ RightOutlined,+} from '@ant-design/icons';+import { Button, Divider, Select } from 'antd';+import React, { memo } from 'react';+import { connect, useDispatch, useSelector } from 'react-redux';+import { bindActionCreators, Dispatch } from 'redux';+import { ThunkDispatch } from 'redux-thunk';+import { getLogs } from 'store/actions/logs/getLogs';+import { AppState } from 'store/reducers';+import AppActions from 'types/actions';+import {+ GET_NEXT_LOG_LINES,+ GET_PREVIOUS_LOG_LINES,+ RESET_ID_START_AND_END,+ SET_LOG_LINES_PER_PAGE,+} from 'types/actions/logs';+import { GlobalReducer } from 'types/reducer/globalTime';+import ILogsReducer from 'types/reducer/logs';++import { Container } from './styles';++const { Option } = Select;++const ITEMS_PER_PAGE_OPTIONS = [25, 50, 100, 200];++function LogControls({ getLogs }) {+ const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(+ (state) => state.globalTime,+ );+ const {+ logLinesPerPage,+ idStart,+ idEnd,+ liveTail,+ searchFilter: { queryString },+ } = useSelector<AppState, ILogsReducer>((state) => state.logs);+ const dispatch = useDispatch();++ const handleLogLinesPerPageChange = (e: number) => {+ dispatch({+ type: SET_LOG_LINES_PER_PAGE,+ payload: e,+ });+ };++ const handleGoToLatest = () => {+ dispatch({+ type: RESET_ID_START_AND_END,+ });++ if (liveTail === 'STOPPED')+ getLogs({+ q: queryString,+ limit: logLinesPerPage,+ orderBy: 'timestamp',+ order: 'desc',+ timestampStart: minTime,+ timestampEnd: maxTime,+ ...(idStart ? { idGt: idStart } : {}),+ ...(idEnd ? { idLt: idEnd } : {}),+ });+ };++ const handleNavigatePrevious = () => {+ dispatch({+ type: GET_PREVIOUS_LOG_LINES,+ });+ };+ const handleNavigateNext = () => {+ dispatch({+ type: GET_NEXT_LOG_LINES,+ });+ };++ if (liveTail !== 'STOPPED') {+ return null;+ }+ return (+ <Container>+ <Button size="small" type="link" onClick={handleGoToLatest}>+ <FastBackwardOutlined /> Go to latest+ </Button>+ <Divider type="vertical" />+ <Button size="small" type="link" onClick={handleNavigatePrevious}>+ <LeftOutlined /> Previous+ </Button>+ <Button size="small" type="link" onClick={handleNavigateNext}>+ Next <RightOutlined />+ </Button>+ <Select+ style={{ width: 120 }}+ value={logLinesPerPage}+ onChange={handleLogLinesPerPageChange}+ >+ {ITEMS_PER_PAGE_OPTIONS.map((count) => {+ return <Option key={count} value={count}>{`${count} / page`}</Option>;+ })}+ </Select>+ </Container>+ );+}++interface DispatchProps {+ getLogs: () => (dispatch: Dispatch<AppActions>) => void;+}++const mapDispatchToProps = (+ dispatch: ThunkDispatch<unknown, unknown, AppActions>,+): DispatchProps => ({+ getLogs: bindActionCreators(getLogs, dispatch),+});++export default connect(null, mapDispatchToProps)(memo(LogControls));diff --git a/frontend/src/container/LogControls/styles.ts b/frontend/src/container/LogControls/styles.tsnew file mode 100644index 0000000000..304b443c54--- /dev/null+++ b/frontend/src/container/LogControls/styles.ts@@ -0,0 +1,9 @@+import styled from 'styled-components';++export const Container = styled.div`+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: 0.5rem;+ margin-bottom: 0.5rem;+`;diff --git a/frontend/src/container/LogDetailedView/ActionItem.tsx b/frontend/src/container/LogDetailedView/ActionItem.tsxnew file mode 100644index 0000000000..8574124b1e--- /dev/null+++ b/frontend/src/container/LogDetailedView/ActionItem.tsx@@ -0,0 +1,150 @@+import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';+import { Button, Col, Popover } from 'antd';+import getStep from 'lib/getStep';+import { generateFilterQuery } from 'lib/logs/generateFilterQuery';+import React, { Dispatch, memo, useCallback, useMemo } from 'react';+import { connect, useDispatch, useSelector } from 'react-redux';+import { bindActionCreators } from 'redux';+import { ThunkDispatch } from 'redux-thunk';+import { getLogs } from 'store/actions/logs/getLogs';+import { getLogsAggregate } from 'store/actions/logs/getLogsAggregate';+import { AppState } from 'store/reducers';+import AppActions from 'types/actions';+import { SET_SEARCH_QUERY_STRING, TOGGLE_LIVE_TAIL } from 'types/actions/logs';+import { GlobalReducer } from 'types/reducer/globalTime';+import ILogsReducer from 'types/reducer/logs';++const removeJSONStringifyQuotes = (s: string) => {+ if (!s || !s.length) {+ return s;+ }++ if (s[0] === '"' && s[s.length - 1] === '"') {+ return s.slice(1, s.length - 1);+ }+ return s;+};+function ActionItem({ fieldKey, fieldValue, getLogs, getLogsAggregate }) {+ const {+ searchFilter: { queryString },+ logLinesPerPage,+ idStart,+ liveTail,+ idEnd,+ } = useSelector<AppState, ILogsReducer>((store) => store.logs);+ const dispatch = useDispatch();++ const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(+ (state) => state.globalTime,+ );++ const handleQueryAdd = (newQueryString) => {+ let updatedQueryString = queryString || '';++ if (updatedQueryString.length === 0) {+ updatedQueryString += `${newQueryString}`;+ } else {+ updatedQueryString += ` AND ${newQueryString}`;+ }+ dispatch({+ type: SET_SEARCH_QUERY_STRING,+ payload: updatedQueryString,+ });++ if (liveTail === 'STOPPED') {+ getLogs({+ q: updatedQueryString,+ limit: logLinesPerPage,+ orderBy: 'timestamp',+ order: 'desc',+ timestampStart: minTime,+ timestampEnd: maxTime,+ ...(idStart ? { idGt: idStart } : {}),+ ...(idEnd ? { idLt: idEnd } : {}),+ });+ getLogsAggregate({+ timestampStart: minTime,+ timestampEnd: maxTime,+ step: getStep({+ start: minTime,+ end: maxTime,+ inputFormat: 'ns',+ }),+ q: updatedQueryString,+ });+ } else if (liveTail === 'PLAYING') {+ dispatch({+ type: TOGGLE_LIVE_TAIL,+ payload: 'PAUSED',+ });+ setTimeout(+ () =>+ dispatch({+ type: TOGGLE_LIVE_TAIL,+ payload: liveTail,+ }),+ 0,+ );+ }+ };+ const validatedFieldValue = removeJSONStringifyQuotes(fieldValue);+ const PopOverMenuContent = useMemo(+ () => (+ <Col>+ <Button+ type="text"+ size="small"+ onClick={() =>+ handleQueryAdd(+ generateFilterQuery({+ fieldKey,+ fieldValue: validatedFieldValue,+ type: 'IN',+ }),+ )+ }+ >+ <PlusCircleOutlined /> Filter for value+ </Button>+ <br />+ <Button+ type="text"+ size="small"+ onClick={() =>+ handleQueryAdd(+ generateFilterQuery({+ fieldKey,+ fieldValue: validatedFieldValue,+ type: 'NIN',+ }),+ )+ }+ >+ <MinusCircleOutlined /> Filter out value+ </Button>+ </Col>+ ),+ [],+ );+ return (+ <Popover placement="bottomLeft" content={PopOverMenuContent} trigger="click">+ <Button type="text" size="small">+ ...+ </Button>+ </Popover>+ );+}++interface DispatchProps {+ getLogs: () => (dispatch: Dispatch<AppActions>) => void;+ getLogsAggregate: () => (dispatch: Dispatch<AppActions>) => void;+}++const mapDispatchToProps = (+ dispatch: ThunkDispatch<unknown, unknown, AppActions>,+): DispatchProps => ({+ getLogs: bindActionCreators(getLogs, dispatch),+ getLogsAggregate: bindActionCreators(getLogsAggregate, dispatch),+});++export default connect(null, mapDispatchToProps)(memo(ActionItem));diff --git a/frontend/src/container/LogDetailedView/JsonView.tsx b/frontend/src/container/LogDetailedView/JsonView.tsxnew file mode 100644index 0000000000..d4e6df62a1--- /dev/null+++ b/frontend/src/container/LogDetailedView/JsonView.tsx@@ -0,0 +1,34 @@+import { blue } from '@ant-design/colors';+import { CopyFilled } from '@ant-design/icons';+import { Button, Row } from 'antd';+import Editor from 'components/Editor';+import React, { useMemo } from 'react';+import { useCopyToClipboard } from 'react-use';++function JSONView({ logData }) {+ const [_state, copyToClipboard] = useCopyToClipboard();+ const LogJsonData = useMemo(() => JSON.stringify(logData, null, 2), [logData]);+ return (+ <div>+ <Row+ style={{+ justifyContent: 'flex-end',+ margin: '0.5rem 0',+ }}+ >+ <Button+ size="small"+ type="text"+ onClick={(): void => copyToClipboard(LogJsonData)}+ >+ <CopyFilled /> <span style={{ color: blue[5] }}>Copy to Clipboard</span>+ </Button>+ </Row>+ <div style={{ marginTop: '0.5rem' }}>+ <Editor value={LogJsonData} language="json" height="70vh" readOnly />+ </div>+ </div>+ );+}++export default JSONView;diff --git a/frontend/src/container/LogDetailedView/TableView.tsx b/frontend/src/container/LogDetailedView/TableView.tsxnew file mode 100644index 0000000000..9e55e34df9--- /dev/null+++ b/frontend/src/container/LogDetailedView/TableView.tsx@@ -0,0 +1,95 @@+import { blue, orange } from '@ant-design/colors';+import {+ MenuFoldOutlined,+ MinusCircleOutlined,+ PlusCircleFilled,+ PlusCircleOutlined,+} from '@ant-design/icons';+import { Button, Col, Input, Popover, Table, Typography } from 'antd';+import AddToQueryHOC from 'components/Logs/AddToQueryHOC';+import CopyClipboardHOC from 'components/Logs/CopyClipboardHOC';+import flatten from 'flat';+import { fieldSearchFilter } from 'lib/logs/fieldSearch';+import React, { useMemo, useState } from 'react';++import ActionItem from './ActionItem';++function TableView({ logData }) {+ const [fieldSearchInput, setFieldSearchInput] = useState<string>('');++ const flattenLogData = useMemo(() => (logData ? flatten(logData) : null), [+ logData,+ ]);+ if (logData === null) {+ return null;+ }++ const dataSource = Object.keys(flattenLogData)+ .filter((field) => fieldSearchFilter(field, fieldSearchInput))+ .map((key) => {+ return {+ key,+ field: key,+ value: JSON.stringify(flattenLogData[key]),+ };+ });++ const columns = [+ {+ title: 'Action',+ width: 75,+ render: (fieldData) => (+ <ActionItem+ fieldKey={fieldData.field.split('.').slice(-1)}+ fieldValue={fieldData.value}+ />+ ),+ },+ {+ title: 'Field',+ dataIndex: 'field',+ key: 'field',+ width: '35%',+ render: (field: string) => (+ <AddToQueryHOC+ fieldKey={field.split('.').slice(-1)}+ fieldValue={flattenLogData[field]}+ >+ {' '}+ <span style={{ color: blue[4] }}>{field}</span>+ </AddToQueryHOC>+ ),+ },+ {+ title: 'Value',+ dataIndex: 'value',+ key: 'value',+ ellipsis: false,+ render: (field) => (+ <CopyClipboardHOC textToCopy={field}>+ <span style={{ color: orange[6] }}>{field}</span>+ </CopyClipboardHOC>+ ),+ width: '60%',+ },+ ];+ return (+ <div style={{ position: 'relative' }}>+ <Input+ placeholder="Search field names"+ size="large"+ value={fieldSearchInput}+ onChange={(e) => setFieldSearchInput(e.target.value)}+ />+ <Table+ // scroll={{ x: true }}+ tableLayout='fixed'+ dataSource={dataSource}+ columns={columns}+ pagination={false}+ />+ </div>+ );+}++export default TableView;diff --git a/frontend/src/container/LogDetailedView/index.tsx b/frontend/src/container/LogDetailedView/index.tsxnew file mode 100644index 0000000000..24196b42cd--- /dev/null+++ b/frontend/src/container/LogDetailedView/index.tsx@@ -0,0 +1,51 @@+import { Drawer, Tabs } from 'antd';+import React from 'react';+import { useDispatch, useSelector } from 'react-redux';+import { AppState } from 'store/reducers';+import { SET_DETAILED_LOG_DATA } from 'types/actions/logs';+import ILogsReducer from 'types/reducer/logs';++import JSONView from './JsonView';+import TableView from './TableView';++const { TabPane } = Tabs;++function LogDetailedView() {+ const { detailedLog } = useSelector<AppState, ILogsReducer>(+ (state) => state.logs,+ );+ const dispatch = useDispatch();+ const onDrawerClose = () => {+ dispatch({+ type: SET_DETAILED_LOG_DATA,+ payload: null,+ });+ };++ return (+ <div style={{}}>+ <Drawer+ width="60%"+ title="Log Details"+ placement="right"+ closable+ mask={false}+ onClose={onDrawerClose}+ visible={detailedLog !== null}+ getContainer={false}+ style={{ overscrollBehavior: 'contain' }}+ >+ <Tabs defaultActiveKey="1">+ <TabPane tab="Table" key="1">+ <TableView logData={detailedLog} />+ </TabPane>+ <TabPane tab="JSON" key="2">+ <JSONView logData={detailedLog} />+ </TabPane>+ </Tabs>+ </Drawer>+ </div>+ );+}++export default LogDetailedView;diff --git a/frontend/src/container/LogLiveTail/OptionIcon.tsx b/frontend/src/container/LogLiveTail/OptionIcon.tsxnew file mode 100644index 0000000000..0698516c33--- /dev/null+++ b/frontend/src/container/LogLiveTail/OptionIcon.tsx@@ -0,0 +1,23 @@+import React from 'react';++function OptionIcon({ isDarkMode }) {+ return (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ x="0px"+ y="0px"+ width="1rem"+ height="1rem"+ viewBox="0 0 52 52"+ enableBackground="new 0 0 52 52"+ fill={isDarkMode ? "#eee" : '#222'}+ >+ <path+ d="M20,44c0-3.3,2.7-6,6-6s6,2.7,6,6s-2.7,6-6,6S20,47.3,20,44z M20,26c0-3.3,2.7-6,6-6s6,2.7,6,6s-2.7,6-6,6+ S20,29.3,20,26z M20,8c0-3.3,2.7-6,6-6s6,2.7,6,6s-2.7,6-6,6S20,11.3,20,8z"+ />+ </svg>+ );+}++export default OptionIcon;diff --git a/frontend/src/container/LogLiveTail/index.tsx b/frontend/src/container/LogLiveTail/index.tsxnew file mode 100644index 0000000000..bc699c82a1--- /dev/null+++ b/frontend/src/container/LogLiveTail/index.tsx@@ -0,0 +1,241 @@+import { green, red } from '@ant-design/colors';+import {+ ArrowRightOutlined,+ IeSquareFilled,+ PauseOutlined,+ PlayCircleOutlined,+ PlaySquareFilled,+ ReloadOutlined,+ StopFilled,+} from '@ant-design/icons';+import { fetchEventSource } from '@microsoft/fetch-event-source';+import { Button, Card, Popover, Row, Select, Typography } from 'antd';+import getLocalStorageKey from 'api/browser/localstorage/get';+import { LiveTail } from 'api/logs/livetail';+import { LOCALSTORAGE } from 'constants/localStorage';+import dayjs from 'dayjs';+import { debounce, throttle } from 'lodash-es';+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import { useDispatch, useSelector } from 'react-redux';+import { AppState } from 'store/reducers';+import {+ FLUSH_LOGS,+ PUSH_LIVE_TAIL_EVENT,+ SET_LIVE_TAIL_START_TIME,+ TOGGLE_LIVE_TAIL,+} from 'types/actions/logs';+import { TLogsLiveTailState } from 'types/api/logs/liveTail';+import AppReducer from 'types/reducer/app';+import ILogsReducer from 'types/reducer/logs';++import OptionIcon from './OptionIcon';+import { TimePickerCard, TimePickerSelect } from './styles';++const { Option } = Select;++const TIME_PICKER_OPTIONS = [+ {+ value: 5,+ label: '5m',+ },+ {+ value: 15,+ label: '15m',+ },+ {+ value: 30,+ label: '30m',+ },+ {+ value: 60,+ label: '1hr',+ },+ {+ value: 360,+ label: '6hrs',+ },+ {+ value: 720,+ label: '12hrs',+ },+];++function LogLiveTail() {+ const {+ liveTail,+ searchFilter: { queryString },+ liveTailStartRange,+ logs,+ } = useSelector<AppState, ILogsReducer>((state) => state.logs);+ const { isDarkMode } = useSelector<AppState, AppReducer>((state) => state.app);+ const dispatch = useDispatch();+ const handleLiveTail = (toggleState: TLogsLiveTailState) => {+ dispatch({+ type: TOGGLE_LIVE_TAIL,+ payload: toggleState,+ });+ };++ const batchedEventsRef = useRef([]);++ const pushLiveLog = useCallback(+ throttle(() => {+ dispatch({+ type: PUSH_LIVE_TAIL_EVENT,+ payload: batchedEventsRef.current.reverse(),+ });+ // console.log('DISPATCH', batchedEventsRef.current.length);+ batchedEventsRef.current = [];+ }, 1500),+ [],+ );++ const batchLiveLog = (e) => {+ // console.log('EVENT BATCHED');+ batchedEventsRef.current.push(JSON.parse(e.data));+ pushLiveLog();+ };++ // This ref depicts thats whether the live tail is played from paused state or not.+ const liveTailSourceRef = useRef(null);+ useEffect(() => {+ if (liveTail === 'PLAYING') {+ // console.log('Starting Live Tail', logs.length);+ const timeStamp = dayjs().subtract(liveTailStartRange, 'minute').valueOf();+ const queryParams = new URLSearchParams({+ ...(queryString ? { q: queryString } : {}),+ timestampStart: timeStamp,+ ...(liveTailSourceRef.current && logs.length > 0+ ? {+ idGt: logs[0].id,+ }+ : {}),+ });+ const source = LiveTail(queryParams.toString());+ liveTailSourceRef.current = source;+ source.onmessage = function (e) {+ // pushLiveLog(e)+ batchLiveLog(e);+ };+ source.onopen = function (event) {+ // console.log('open event');+ // console.log(event);+ };+ source.onerror = function (event) {+ // console.log(event);+ source.close();+ dispatch({+ type: TOGGLE_LIVE_TAIL,+ payload: false,+ });+ };+ } else if (liveTailSourceRef.current) {+ liveTailSourceRef.current?.close();+ }++ if (liveTail === 'STOPPED') {+ liveTailSourceRef.current = null;+ }+ }, [liveTail]);++ const handleLiveTailStart = () => {+ handleLiveTail('PLAYING');+ if (!liveTailSourceRef.current) {+ dispatch({+ type: FLUSH_LOGS,+ });+ }+ };++ const OptionsPopOverContent = useMemo(+ () => (+ <TimePickerSelect+ disabled={liveTail === 'PLAYING'}+ value={liveTailStartRange}+ onChange={(value) => {+ dispatch({+ type: SET_LIVE_TAIL_START_TIME,+ payload: value,+ });+ }}+ >+ {TIME_PICKER_OPTIONS.map((optionData) => (+ <Option key={optionData.label} value={optionData.value}>+ Last {optionData.label}+ </Option>+ ))}+ </TimePickerSelect>+ ),+ [dispatch, liveTail, liveTailStartRange],+ );+ return (+ <TimePickerCard>+ <Row+ style={{ gap: '0.5rem', alignItems: 'center', justifyContent: 'center' }}+ >+ <div>+ {liveTail === 'PLAYING' ? (+ <Button+ type="primary"+ onClick={() => handleLiveTail('PAUSED')}+ title="Pause live tail"+ style={{ background: green[6] }}+ >+ Pause <PauseOutlined />+ </Button>+ ) : (+ <Button+ type="primary"+ onClick={handleLiveTailStart}+ title="Start live tail"+ >+ Go Live <PlayCircleOutlined />+ </Button>+ )}+ {liveTail !== 'STOPPED' && (+ <Button+ type="dashed"+ onClick={() => handleLiveTail('STOPPED')}+ title="Exit live tail"+ >+ <div+ style={{+ height: '0.8rem',+ width: '0.8rem',+ background: isDarkMode ? '#eee' : '#222',+ borderRadius: '0.1rem',+ }}+ />+ </Button>+ )}+ </div>++ <Popover+ placement="bottomRight"+ title="Select Live Tail Timing"+ trigger="click"+ content={OptionsPopOverContent}+ >+ <span+ style={{+ padding: '0.3rem 0.4rem 0.3rem 0',+ display: 'flex',+ justifyContent: 'center',+ alignContent: 'center',+ }}+ >+ <OptionIcon isDarkMode={isDarkMode} />+ </span>+ </Popover>+ </Row>+ </TimePickerCard>+ );+}++export default LogLiveTail;diff --git a/frontend/src/container/LogLiveTail/styles.ts b/frontend/src/container/LogLiveTail/styles.tsnew file mode 100644index 0000000000..4e8691dbd0--- /dev/null+++ b/frontend/src/container/LogLiveTail/styles.ts@@ -0,0 +1,12 @@+import { Card, Select } from 'antd';+import styled from 'styled-components';++export const TimePickerCard = styled(Card)`+ .ant-card-body {+ padding: 0;+ }+`;++export const TimePickerSelect = styled(Select)`+ min-width: 100px;+`;diff --git a/frontend/src/container/Logs/index.tsx b/frontend/src/container/Logs/index.tsxnew file mode 100644index 0000000000..e7c8069ef8--- /dev/null+++ b/frontend/src/container/Logs/index.tsx@@ -0,0 +1,68 @@+import { Divider, Row } from 'antd';+import LogControls from 'container/LogControls';+import LogDetailedView from 'container/LogDetailedView';+import LogLiveTail from 'container/LogLiveTail';+import LogsAggregate from 'container/LogsAggregate';+import LogsFilters from 'container/LogsFilters';+import SearchFilter from 'container/LogsSearchFilter';+import LogsTable from 'container/LogsTable';+import React, { memo, useEffect, useMemo } from 'react';+import { connect, useDispatch } from 'react-redux';+import { useLocation } from 'react-router-dom';+import { bindActionCreators, Dispatch } from 'redux';+import { ThunkDispatch } from 'redux-thunk';+import { GetLogsFields } from 'store/actions/logs/getFields';+import AppActions from 'types/actions';+import { SET_SEARCH_QUERY_STRING } from 'types/actions/logs';++function Logs({ getLogsFields }) {+ const { search } = useLocation();++ const urlQuery = useMemo(() => {+ return new URLSearchParams(search);+ }, [search]);++ const dispatch = useDispatch();++ useEffect(() => {+ dispatch({+ type: SET_SEARCH_QUERY_STRING,+ payload: urlQuery.get('q'),+ });+ }, [dispatch]);++ useEffect(() => {+ getLogsFields();+ }, [getLogsFields]);++ return (+ <div style={{ position: 'relative' }}>+ <Row style={{ justifyContent: 'center', alignItems: 'center' }}>+ <SearchFilter />+ <Divider type='vertical' style={{ height: '2rem' }} />+ <LogLiveTail />+ </Row>+ <LogsAggregate />+ <LogControls />+ <Divider style={{ margin: 0 }} />+ <Row gutter={20} style={{ flexWrap: 'nowrap' }}>+ <LogsFilters flex="450px" />+ <Divider type="vertical" style={{ height: '100%', margin: 0 }} />+ <LogsTable flex="auto" />+ </Row>+ <LogDetailedView />+ </div>+ );+}++interface DispatchProps {+ getLogsFields: () => (dispatch: Dispatch<AppActions>) => void;+}++const mapDispatchToProps = (+ dispatch: ThunkDispatch<unknown, unknown, AppActions>,+): DispatchProps => ({+ getLogsFields: bindActionCreators(GetLogsFields, dispatch),+});++export default connect(null, mapDispatchToProps)(memo(Logs));diff --git a/frontend/src/container/LogsAggregate/index.tsx b/frontend/src/container/LogsAggregate/index.tsxnew file mode 100644index 0000000000..b0f3e48048--- /dev/null+++ b/frontend/src/container/LogsAggregate/index.tsx@@ -0,0 +1,135 @@+import { blue } from '@ant-design/colors';+import Graph from 'components/Graph';+import Spinner from 'components/Spinner';+import dayjs from 'dayjs';+import getStep from 'lib/getStep';+import React, { memo, useEffect, useRef } from 'react';+import { connect, useDispatch, useSelector } from 'react-redux';+import { bindActionCreators, Dispatch } from 'redux';+import { ThunkDispatch } from 'redux-thunk';+import { getLogsAggregate } from 'store/actions/logs/getLogsAggregate';+import { AppState } from 'store/reducers';+import AppActions from 'types/actions';+import { GlobalReducer } from 'types/reducer/globalTime';+import ILogsReducer from 'types/reducer/logs';++import { Container } from './styles';++function LogsAggregate({ getLogsAggregate }) {+ const {+ searchFilter: { queryString },+ logs,+ logLinesPerPage,+ idEnd,+ idStart,+ isLoading,+ isLoadingAggregate,+ logsAggregate,+ liveTail,+ liveTailStartRange,+ } = useSelector<AppState, ILogsReducer>((state) => state.logs);++ const dispatch = useDispatch();+ const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(+ (state) => state.globalTime,+ );++ const reFetchIntervalRef = useRef(null);+ useEffect(() => {+ // console.log('LIVE TAIL LOG AGG', liveTail)+ switch (liveTail) {+ case 'STOPPED': {+ if (reFetchIntervalRef.current) {+ clearInterval(reFetchIntervalRef.current);+ }+ reFetchIntervalRef.current = null;+ getLogsAggregate({+ timestampStart: minTime,+ timestampEnd: maxTime,+ step: getStep({+ start: minTime,+ end: maxTime,+ inputFormat: 'ns',+ }),+ q: queryString,+ ...(idStart ? { idGt: idStart } : {}),+ ...(idEnd ? { idLt: idEnd } : {}),+ });+ break;+ }++ case 'PLAYING': {+ const aggregateCall = () => {+ const startTime =+ dayjs().subtract(liveTailStartRange, 'minute').valueOf() * 1e6;+ const endTime = dayjs().valueOf() * 1e6;+ getLogsAggregate({+ timestampStart: startTime,+ timestampEnd: endTime,+ step: getStep({+ start: startTime,+ end: endTime,+ inputFormat: 'ns',+ }),+ q: queryString,+ ...(idStart ? {idGt: idStart } : {}),+ ...(idEnd ? { idLt: idEnd } : {}),+ });+ };+ aggregateCall();+ reFetchIntervalRef.current = setInterval(aggregateCall, 60000);+ // console.log('LA Play', reFetchIntervalRef.current);+ break;+ }+ case 'PAUSED': {+ // console.log('LA Pause', reFetchIntervalRef.current);+ if (reFetchIntervalRef.current) {+ clearInterval(reFetchIntervalRef.current);+ }+ break;+ }+ default: {+ break;+ }+ }+ }, [getLogsAggregate, maxTime, minTime, liveTail]);++ const data = {+ labels: logsAggregate.map((s) => new Date(s.timestamp / 1000000)),+ datasets: [+ {+ // label: 'Span Count',+ data: logsAggregate.map((s) => s.value),+ backgroundColor: blue[4],+ },+ ],+ };++ return (+ <Container>+ {isLoadingAggregate ? (+ <Spinner size="default" height="100%" />+ ) : (+ <Graph+ name="usage"+ data={data}+ type="bar"+ containerHeight="100%"+ animate={false}+ />+ )}+ </Container>+ );+}++interface DispatchProps {+ getLogsAggregate: () => (dispatch: Dispatch<AppActions>) => void;+}++const mapDispatchToProps = (+ dispatch: ThunkDispatch<unknown, unknown, AppActions>,+): DispatchProps => ({+ getLogsAggregate: bindActionCreators(getLogsAggregate, dispatch),+});++export default connect(null, mapDispatchToProps)(memo(LogsAggregate));diff --git a/frontend/src/container/LogsAggregate/styles.ts b/frontend/src/container/LogsAggregate/styles.tsnew file mode 100644index 0000000000..727af4036b--- /dev/null+++ b/frontend/src/container/LogsAggregate/styles.ts@@ -0,0 +1,11 @@+import { Card } from 'antd';+import styled from 'styled-components';++export const Container = styled(Card)`+ position: relative;+ margin: 0.5rem 0;+ .ant-card-body {+ height: 20vh;+ min-height: 200px;+ }+`;diff --git a/frontend/src/container/LogsFilters/FieldItem.tsx b/frontend/src/container/LogsFilters/FieldItem.tsxnew file mode 100644index 0000000000..aabab390c8--- /dev/null+++ b/frontend/src/container/LogsFilters/FieldItem.tsx@@ -0,0 +1,54 @@+import {+ CloseCircleFilled,+ CloseOutlined,+ LoadingOutlined,+} from '@ant-design/icons';+import { Button, Popover, Spin } from 'antd';+import Spinner from 'components/Spinner';+import React, { useRef, useState } from 'react';+import { useSelector } from 'react-redux';+import { useHover, useHoverDirty } from 'react-use';+import { AppState } from 'store/reducers';+import AppReducer from 'types/reducer/app';++import { Field } from './styles';++export function FieldItem({+ name,+ buttonIcon,+ buttonOnClick,+ fieldData,+ fieldIndex,+ isLoading,+ iconHoverText+}) {+ const [isHovered, setIsHovered] = useState(false);+ const { isDarkMode } = useSelector<AppState, AppReducer>((state) => state.app);+ return (+ <Field+ onMouseEnter={() => {+ setIsHovered(true);+ }}+ onMouseLeave={() => setIsHovered(false)}+ isDarkMode={isDarkMode}+ >+ <span>{name}</span>+ {isLoading ? (+ <Spin spinning size="small" indicator={<LoadingOutlined spin />} />+ ) : (+ isHovered &&+ buttonOnClick && (+ <Popover content={<span>{iconHoverText}</span>}>+ <Button+ type="text"+ size="small"+ icon={buttonIcon}+ onClick={() => buttonOnClick({ fieldData, fieldIndex })}+ style={{ color: 'inherit', padding: 0, height: '1rem', width: '1rem' }}+ />+ </Popover>+ )+ )}+ </Field>+ );+}diff --git a/frontend/src/container/LogsFilters/index.tsx b/frontend/src/container/LogsFilters/index.tsxnew file mode 100644index 0000000000..1a12f42965--- /dev/null+++ b/frontend/src/container/LogsFilters/index.tsx@@ -0,0 +1,145 @@+import { red } from '@ant-design/colors';+import {+ CloseCircleFilled,+ CloseOutlined,+ PlusCircleFilled,+ PlusCircleOutlined,+} from '@ant-design/icons';+import { Input } from 'antd';+import AddToSelectedFields from 'api/logs/AddToSelectedField';+import RemoveSelectedField from 'api/logs/RemoveFromSelectedField';+import CategoryHeading from 'components/Logs/CategoryHeading';+import { fieldSearchFilter } from 'lib/logs/fieldSearch';+import React, { memo, useState } from 'react';+import { connect, useSelector } from 'react-redux';+import { bindActionCreators, Dispatch } from 'redux';+import { ThunkDispatch } from 'redux-thunk';+import { GetLogsFields } from 'store/actions/logs/getFields';+import { AppState } from 'store/reducers';+import AppActions from 'types/actions';+import ILogsReducer from 'types/reducer/logs';++import { FieldItem } from './FieldItem';+import {+ CategoryContainer,+ Container,+ ExtractField,+ Field,+ FieldContainer,+} from './styles';++const RESTRICTED_SELECTED_FIELDS = ['timestamp', 'id'];++function LogsFilters({ getLogsFields }) {+ const {+ fields: { interesting, selected },+ } = useSelector<AppState, ILogsReducer>((state) => state.logs);++ const [selectedFieldLoading, setSelectedFieldLoading] = useState([]);+ const [interestingFieldLoading, setInterestingFieldLoading] = useState([]);++ const [filterValuesInput, setFilterValuesInput] = useState('');+ const handleSearch = (e) => {+ setFilterValuesInput(e.target.value);+ };++ const handleAddInterestingToSelected = async ({ fieldData, fieldIndex }) => {+ setInterestingFieldLoading((prevState) => {+ prevState.push(fieldIndex);+ return [...prevState];+ });++ await AddToSelectedFields({+ ...fieldData,+ selected: true,+ });+ getLogsFields();++ setInterestingFieldLoading(+ interestingFieldLoading.filter((e) => e !== fieldIndex),+ );+ };+ const handleRemoveSelectedField = async ({ fieldData, fieldIndex }) => {+ setSelectedFieldLoading((prevState) => {+ prevState.push(fieldIndex);+ return [...prevState];+ });++ await RemoveSelectedField({+ ...fieldData,+ selected: false,+ });++ getLogsFields();++ setSelectedFieldLoading(+ interestingFieldLoading.filter((e) => e !== fieldIndex),+ );+ };+ return (+ <Container>+ <Input+ placeholder="Filter Values"+ onInput={handleSearch}+ style={{ width: '100%' }}+ value={filterValuesInput}+ onChange={handleSearch}+ />++ <CategoryContainer>+ <CategoryHeading>SELECTED FIELDS</CategoryHeading>+ <FieldContainer>+ {selected+ .filter((field) => fieldSearchFilter(field.name, filterValuesInput))+ .map((field, idx) => (+ <FieldItem+ key={field + idx}+ name={field.name}+ fieldData={field}+ fieldIndex={idx}+ buttonIcon={<CloseOutlined style={{ color: red[5] }} />}+ buttonOnClick={+ !RESTRICTED_SELECTED_FIELDS.includes(field.name) &&+ handleRemoveSelectedField+ }+ isLoading={selectedFieldLoading.includes(idx)}+ iconHoverText="Remove from Selected Fields"+ />+ ))}+ </FieldContainer>+ </CategoryContainer>+ <CategoryContainer>+ <CategoryHeading>INTERESTING FIELDS</CategoryHeading>+ <FieldContainer>+ {interesting+ .filter((field) => fieldSearchFilter(field.name, filterValuesInput))+ .map((field, idx) => (+ <FieldItem+ key={field + idx}+ name={field.name}+ fieldData={field}+ fieldIndex={idx}+ buttonIcon={<PlusCircleFilled />}+ buttonOnClick={handleAddInterestingToSelected}+ isLoading={interestingFieldLoading.includes(idx)}+ iconHoverText="Add to Selected Fields"+ />+ ))}+ </FieldContainer>+ </CategoryContainer>+ {/* <ExtractField>Extract Fields</ExtractField> */}+ </Container>+ );+}++interface DispatchProps {+ getLogsFields: () => (dispatch: Dispatch<AppActions>) => void;+}++const mapDispatchToProps = (+ dispatch: ThunkDispatch<unknown, unknown, AppActions>,+): DispatchProps => ({+ getLogsFields: bindActionCreators(GetLogsFields, dispatch),+});++export default connect(null, mapDispatchToProps)(memo(LogsFilters));diff --git a/frontend/src/container/LogsFilters/styles.ts b/frontend/src/container/LogsFilters/styles.tsnew file mode 100644index 0000000000..56ffaebafe--- /dev/null+++ b/frontend/src/container/LogsFilters/styles.ts@@ -0,0 +1,36 @@+import { blue, grey } from '@ant-design/colors';+import { Col, Typography } from 'antd';+import styled from 'styled-components';++export const Container = styled(Col)`+ padding-top: 0.3rem;+ min-width: 250px;+ max-width: 350px;+`;++export const CategoryContainer = styled.div`+ margin: 1rem 0;+ padding-left: 0.2rem;+`;++export const FieldContainer = styled(Typography.Text)`+ margin: 0.2rem 0;+ color: ${blue[4]};+`;++export const Field = styled.div<{ isDarkMode: boolean }>`+ border-radius: 0.5rem;+ padding: 0.3rem 0.5rem;+ display: flex;+ justify-content: space-between;+ align-items: center;+ &:hover {+ background: ${({ isDarkMode }): string => {+ return isDarkMode ? grey[7] : '#ddd';+ }};+ }+`;++export const ExtractField = styled(Typography.Text)`+ color: ${blue[4]};+`;diff --git a/frontend/src/container/LogsSearchFilter/SearchFields/FieldKey.tsx b/frontend/src/container/LogsSearchFilter/SearchFields/FieldKey.tsxnew file mode 100644index 0000000000..f99e18dfea--- /dev/null+++ b/frontend/src/container/LogsSearchFilter/SearchFields/FieldKey.tsx@@ -0,0 +1,15 @@+import { Typography } from 'antd';+import React from 'react';++function FieldKey({ name, type }) {+ return (+ <span style={{ margin: '0.25rem 0', display: 'flex', gap: '0.5rem' }}>+ <Typography.Text>{name}</Typography.Text>+ <Typography.Text type="secondary" italic>+ {type}+ </Typography.Text>+ </span>+ );+}++export default FieldKey;diff --git a/frontend/src/container/LogsSearchFilter/SearchFields/QueryBuilder/QueryBuilder.tsx b/frontend/src/container/LogsSearchFilter/SearchFields/QueryBuilder/QueryBuilder.tsxnew file mode 100644index 0000000000..6db23e3462--- /dev/null+++ b/frontend/src/container/LogsSearchFilter/SearchFields/QueryBuilder/QueryBuilder.tsx@@ -0,0 +1,227 @@+import { CloseOutlined } from '@ant-design/icons';+import { Button, Input, Select, Typography } from 'antd';+import CategoryHeading from 'components/Logs/CategoryHeading';+import {+ ConditionalOperators,+ QueryOperatorsMultiVal,+ QueryOperatorsSingleVal,+ QueryTypes,+} from 'lib/logql/tokens';+import { chunk, cloneDeep, debounce, flatten } from 'lodash-es';+import React, {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import { useSelector } from 'react-redux';+import { useHoverDirty, useLocation } from 'react-use';+import { AppState } from 'store/reducers';+import ILogsReducer from 'types/reducer/logs';+import { v4 } from 'uuid';++import FieldKey from '../FieldKey';+import { QueryConditionContainer, QueryFieldContainer } from '../styles';+import { createParsedQueryStructure } from '../utils';++const { Option } = Select;+function QueryField({ query, queryIndex, onUpdate, onDelete }) {+ const {+ fields: { selected },+ } = useSelector<AppState, ILogsReducer>((store) => store.logs);++ const getFieldType = (inputKey) => {+ for (const selectedField of selected) {+ if (inputKey === selectedField.name) {+ return selectedField.type;+ }+ }+ return '';+ };+ const fieldType = useMemo(() => getFieldType(query[0].value), [+ query,+ selected,+ ]);+ const handleChange = (qIdx, value) => {+ query[qIdx].value = value || '';++ if (qIdx === 1) {+ if (Object.values(QueryOperatorsMultiVal).includes(value)) {+ if (!Array.isArray(query[2].value)) {+ query[2].value = [];+ }+ } else if (Object.values(QueryOperatorsSingleVal).includes(value)) {+ if (Array.isArray(query[2].value)) {+ query[2].value = '';+ }+ }+ }+ onUpdate(query, queryIndex);+ };++ const handleClear = () => {+ onDelete(queryIndex);+ };+ if (!Array.isArray(query)) {+ return null;+ }++ return (+ <QueryFieldContainer+ style={{ ...(queryIndex === 0 && { gridColumnStart: 2 }) }}+ >+ <div style={{ flex: 1, minWidth: 100 }}>+ <FieldKey name={query[0] && query[0].value} type={fieldType} />+ </div>+ <Select+ defaultActiveFirstOption={false}+ placeholder="Select Operator"+ defaultValue={+ query[1] && query[1].value ? query[1].value.toUpperCase() : null+ }+ onChange={(e) => handleChange(1, e)}+ style={{ minWidth: 150 }}+ >+ {Object.values({+ ...QueryOperatorsMultiVal,+ ...QueryOperatorsSingleVal,+ }).map((cond) => (+ <Option key={cond} value={cond} label={cond} />+ ))}+ </Select>+ <div style={{ flex: 2 }}>+ {Array.isArray(query[2].value) ||+ Object.values(QueryOperatorsMultiVal).some(+ (op) => op.toUpperCase() === query[1].value?.toUpperCase(),+ ) ? (+ <Select+ mode="tags"+ style={{ width: '100%' }}+ onChange={(e) => handleChange(2, e)}+ defaultValue={(query[2] && query[2].value) || []}+ notFoundContent={null}+ />+ ) : (+ <Input+ onChange={(e) => handleChange(2, e.target.value)}+ style={{ width: '100%' }}+ defaultValue={query[2] && query[2].value}+ />+ )}+ </div>++ <Button+ icon={<CloseOutlined />}+ type="text"+ size="small"+ onClick={handleClear}+ />+ </QueryFieldContainer>+ );+}+function QueryConditionField({ query, queryIndex, onUpdate }) {+ return (+ <QueryConditionContainer>+ <Select+ defaultValue={query.value.toUpperCase()}+ onChange={(e) => {+ onUpdate({ ...query, value: e }, queryIndex);+ }}+ style={{ width: '100%' }}+ >+ {Object.values(ConditionalOperators).map((cond) => (+ <Option key={cond} value={cond} label={cond} />+ ))}+ </Select>+ </QueryConditionContainer>+ );+}+const hashCode = (s) => {+ if (!s) {+ return '0';+ }+ return `${Math.abs(+ s.split('').reduce((a, b) => {+ a = (a << 5) - a + b.charCodeAt(0);+ return a & a;+ }, 0),+ )}`;+};++function QueryBuilder({ updateParsedQuery }) {+ const {+ searchFilter: { parsedQuery },+ } = useSelector<AppState, ILogsReducer>((store) => store.logs);++ const keyPrefixRef = useRef(hashCode(JSON.stringify(parsedQuery)));+ const [keyPrefix, setKeyPrefix] = useState(keyPrefixRef.current);+ const generatedQueryStructure = createParsedQueryStructure(parsedQuery);++ useEffect(() => {+ const incomingHashCode = hashCode(JSON.stringify(parsedQuery));+ if (incomingHashCode !== keyPrefixRef.current) {+ keyPrefixRef.current = incomingHashCode;+ setKeyPrefix(incomingHashCode);+ }+ }, [parsedQuery]);++++ const handleUpdate = (query, queryIndex): void => {+ const updatedParsedQuery = generatedQueryStructure;+ updatedParsedQuery[queryIndex] = query;++ const flatParsedQuery = flatten(updatedParsedQuery).filter((q) => q.value);+ keyPrefixRef.current = hashCode(JSON.stringify(flatParsedQuery));+ updateParsedQuery(flatParsedQuery);+ };++ const handleDelete = (queryIndex) => {+ const updatedParsedQuery = generatedQueryStructure;+ updatedParsedQuery.splice(queryIndex - 1, 2);++ const flatParsedQuery = flatten(updatedParsedQuery).filter((q) => q.value);+ keyPrefixRef.current = v4();+ updateParsedQuery(flatParsedQuery);+ };++ const QueryUI = () =>+ generatedQueryStructure.map((query, idx) => {+ if (Array.isArray(query))+ return (+ <QueryField+ key={keyPrefix + idx}+ query={query}+ queryIndex={idx}+ onUpdate={handleUpdate}+ onDelete={handleDelete}+ />+ );++ return (+ <QueryConditionField+ key={keyPrefix + idx}+ query={query}+ queryIndex={idx}+ onUpdate={handleUpdate}+ />+ );+ });+ return (+ <div>+ <CategoryHeading>LOG QUERY BUILDER</CategoryHeading>+ <div+ style={{+ display: 'grid',+ gridTemplateColumns: '80px 1fr',+ margin: '0.5rem 0',+ }}+ >+ {QueryUI()}+ </div>+ </div>+ );+}++export default QueryBuilder;diff --git a/frontend/src/container/LogsSearchFilter/SearchFields/Suggestions.tsx b/frontend/src/container/LogsSearchFilter/SearchFields/Suggestions.tsxnew file mode 100644index 0000000000..b6bd42e391--- /dev/null+++ b/frontend/src/container/LogsSearchFilter/SearchFields/Suggestions.tsx@@ -0,0 +1,53 @@+import { Button, Typography } from 'antd';+import CategoryHeading from 'components/Logs/CategoryHeading';+import { map } from 'lodash-es';+import React from 'react';+import { useDispatch, useSelector } from 'react-redux';+import { AppState } from 'store/reducers';+import { ADD_SEARCH_FIELD_QUERY_STRING } from 'types/actions/logs';+import ILogsReducer from 'types/reducer/logs';++import FieldKey from './FieldKey';++function SuggestedItem({ name, type }) {+ const dispatch = useDispatch();++ const addSuggestedField = () => {+ dispatch({+ type: ADD_SEARCH_FIELD_QUERY_STRING,+ payload: name,+ });+ };+ return (+ <Button+ type="text"+ style={{ display: 'block', padding: '0.2rem' }}+ onClick={addSuggestedField}+ >+ <FieldKey name={name} type={type} />+ </Button>+ );+}++function Suggestions() {+ const {+ fields: { selected },+ } = useSelector<AppState, ILogsReducer>((store) => store.logs);++ return (+ <div>+ <CategoryHeading>SUGGESTIONS</CategoryHeading>+ <div>+ {map(selected, (field) => (+ <SuggestedItem+ key={JSON.stringify(field)}+ name={field.name}+ type={field.type}+ />+ ))}+ </div>+ </div>+ );+}++export default Suggestions;diff --git a/frontend/src/container/LogsSearchFilter/SearchFields/index.tsx b/frontend/src/container/LogsSearchFilter/SearchFields/index.tsxnew file mode 100644index 0000000000..7aff84ee69--- /dev/null+++ b/frontend/src/container/LogsSearchFilter/SearchFields/index.tsx@@ -0,0 +1,14 @@+import React from 'react';+import QueryBuilder from './QueryBuilder/QueryBuilder';+import Suggestions from './Suggestions';++function SearchFields({updateParsedQuery}): JSX.Element {++ return (+ <>+ <QueryBuilder updateParsedQuery={updateParsedQuery} />+ <Suggestions />+ </>+ );+}+export default SearchFields;diff --git a/frontend/src/container/LogsSearchFilter/SearchFields/styles.tsx b/frontend/src/container/LogsSearchFilter/SearchFields/styles.tsxnew file mode 100644index 0000000000..3ec67d2fd7--- /dev/null+++ b/frontend/src/container/LogsSearchFilter/SearchFields/styles.tsx@@ -0,0 +1,20 @@+import { blue } from '@ant-design/colors';+import styled from 'styled-components';++export const QueryFieldContainer = styled.div`+ padding: 0.25rem 0.5rem;+ margin: 0.1rem 0.5rem 0;+ display: flex;+ flex-direction: row;+ align-items: center;+ border-radius: 0.25rem;+ gap: 1rem;+ &:hover {+ background: ${blue[6]};+ }+`;++export const QueryConditionContainer = styled.div`+ padding: 0.25rem 0rem;+ margin: 0.1rem 0;+`;diff --git a/frontend/src/container/LogsSearchFilter/SearchFields/utils.ts b/frontend/src/container/LogsSearchFilter/SearchFields/utils.tsnew file mode 100644index 0000000000..6d2e990bf6--- /dev/null+++ b/frontend/src/container/LogsSearchFilter/SearchFields/utils.ts@@ -0,0 +1,57 @@+import { QueryTypes } from 'lib/logql/tokens';++export const queryKOVPair = () => [+ {+ type: QueryTypes.QUERY_KEY,+ value: null,+ },+ {+ type: QueryTypes.QUERY_OPERATOR,+ value: null,+ },+ {+ type: QueryTypes.QUERY_VALUE,+ value: null,+ },+];+export const createParsedQueryStructure = (parsedQuery = []) => {+ if (!parsedQuery.length) {+ return parsedQuery;+ }++ const structuredArray = [queryKOVPair()];++ let cond;+ let qCtr = -1;+ parsedQuery.forEach((query, idx) => {+ if (cond) {+ structuredArray.push(cond);+ structuredArray.push(queryKOVPair());+ cond = null;+ qCtr = -1;+ }+ let stagingArr = structuredArray[structuredArray.length - 1];+ const prevQuery =+ Array.isArray(stagingArr) && qCtr >= 0 ? stagingArr[qCtr] : null;++ if (query.type === QueryTypes.QUERY_KEY) {+ stagingArr[qCtr + 1] = query;+ } else if (+ query.type === QueryTypes.QUERY_OPERATOR &&+ prevQuery &&+ prevQuery.type === QueryTypes.QUERY_KEY+ ) {+ stagingArr[qCtr + 1] = query;+ } else if (+ query.type === QueryTypes.QUERY_VALUE &&+ prevQuery &&+ prevQuery.type === QueryTypes.QUERY_OPERATOR+ ) {+ stagingArr[qCtr + 1] = query;+ } else if (query.type === QueryTypes.CONDITIONAL_OPERATOR) {+ cond = query;+ }+ qCtr++;+ });+ return structuredArray;+};diff --git a/frontend/src/container/LogsSearchFilter/index.tsx b/frontend/src/container/LogsSearchFilter/index.tsxnew file mode 100644index 0000000000..3604a20b17--- /dev/null+++ b/frontend/src/container/LogsSearchFilter/index.tsx@@ -0,0 +1,178 @@+import {+ CloseCircleFilled,+ CloseCircleOutlined,+ CloseSquareOutlined,+} from '@ant-design/icons';+import { Button, Input } from 'antd';+import useClickOutside from 'hooks/useClickOutside';+import getStep from 'lib/getStep';+import { debounce, throttle } from 'lodash-es';+import React, {+ memo,+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from 'react';+import { connect, useDispatch, useSelector } from 'react-redux';+import { useClickAway, useLocation } from 'react-use';+import { bindActionCreators, Dispatch } from 'redux';+import { ThunkDispatch } from 'redux-thunk';+import { getLogs } from 'store/actions/logs/getLogs';+import { getLogsAggregate } from 'store/actions/logs/getLogsAggregate';+import { AppState } from 'store/reducers';+import AppActions from 'types/actions';+import { TOGGLE_LIVE_TAIL } from 'types/actions/logs';+import { GlobalReducer } from 'types/reducer/globalTime';+import ILogsReducer from 'types/reducer/logs';++import SearchFields from './SearchFields';+import { DropDownContainer } from './styles';+import { useSearchParser } from './useSearchParser';++const { Search } = Input;++function SearchFilter({ getLogs, getLogsAggregate }) {+ const {+ queryString,+ updateParsedQuery,+ updateQueryString,+ } = useSearchParser();+ const [showDropDown, setShowDropDown] = useState(false);++ const { logLinesPerPage, idEnd, idStart, liveTail } = useSelector<+ AppState,+ ILogsReducer+ >((state) => state.logs);++ const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(+ (state) => state.globalTime,+ );++ const searchComponentRef = useRef<HTMLDivElement>(null);++ useClickOutside(searchComponentRef, (e: HTMLElement) => {+ // using this hack as overlay span is voilating this condition+ if (+ e.nodeName === 'svg' ||+ e.nodeName === 'path' ||+ e.nodeName === 'span' ||+ e.nodeName === 'button'+ ) {+ return;+ }++ if (+ e.nodeName === 'DIV' &&+ ![+ 'ant-empty-image',+ 'ant-select-item',+ 'ant-col',+ 'ant-select-item-option-content',+ 'ant-select-item-option-active',+ ].find((p) => p.indexOf(e.className) !== -1) &&+ !(e.ariaSelected === 'true') &&+ showDropDown+ ) {+ setShowDropDown(false);+ }+ });+ const { search } = useLocation();+ const dispatch = useDispatch();+ const handleSearch = (customQuery = ''): void => {+ if (liveTail === 'PLAYING') {+ dispatch({+ type: TOGGLE_LIVE_TAIL,+ payload: 'PAUSED',+ });+ setTimeout(+ () =>+ dispatch({+ type: TOGGLE_LIVE_TAIL,+ payload: liveTail,+ }),+ 0,+ );+ } else {+ getLogs({+ q: customQuery || queryString,+ limit: logLinesPerPage,+ orderBy: 'timestamp',+ order: 'desc',+ timestampStart: minTime,+ timestampEnd: maxTime,+ ...(idStart ? { idGt: idStart } : {}),+ ...(idEnd ? { idLt: idEnd } : {}),+ });++ getLogsAggregate({+ timestampStart: minTime,+ timestampEnd: maxTime,+ step: getStep({+ start: minTime,+ end: maxTime,+ inputFormat: 'ns',+ }),+ q: customQuery || queryString,+ });+ }+ setShowDropDown(false);+ };++ const urlQuery = useMemo(() => {+ return new URLSearchParams(search);+ }, [search]);++ useEffect(() => {+ const urlQueryString = urlQuery.get('q');+ if (urlQueryString !== null) handleSearch(urlQueryString);+ }, []);++ return (+ <div ref={searchComponentRef} style={{ flex: 1 }}>+ <Search+ placeholder="Search Filter"+ onFocus={(): void => setShowDropDown(true)}+ value={queryString}+ onChange={(e): void => {+ updateQueryString(e.target.value);+ }}+ onSearch={handleSearch}+ />+ <div style={{ position: 'relative' }}>+ {showDropDown && (+ <DropDownContainer>+ <Button+ type="text"+ onClick={() => setShowDropDown(false)}+ style={{+ position: 'absolute',+ top: 0,+ right: 0,+ }}+ >+ <CloseSquareOutlined size="large" />+ </Button>+ <SearchFields updateParsedQuery={updateParsedQuery} />+ </DropDownContainer>+ )}+ </div>+ </div>+ );+}++interface DispatchProps {+ getLogs: () => (dispatch: Dispatch<AppActions>) => void;+ getLogsAggregate: () => (dispatch: Dispatch<AppActions>) => void;+}++const mapDispatchToProps = (+ dispatch: ThunkDispatch<unknown, unknown, AppActions>,+): DispatchProps => ({+ getLogs: bindActionCreators(getLogs, dispatch),+ getLogsAggregate: bindActionCreators(getLogsAggregate, dispatch),+});++export default connect(null, mapDispatchToProps)(memo(SearchFilter));diff --git a/frontend/src/container/LogsSearchFilter/styles.ts b/frontend/src/container/LogsSearchFilter/styles.tsnew file mode 100644index 0000000000..640881c3fa--- /dev/null+++ b/frontend/src/container/LogsSearchFilter/styles.ts@@ -0,0 +1,12 @@+import { Card } from 'antd';+import styled from 'styled-components';++export const DropDownContainer = styled(Card)`+ top: 0.5rem;+ position: absolute;+ width: 100%;+ z-index: 1;+ .ant-card-body {+ padding: 0.8rem;+ }+`;diff --git a/frontend/src/container/LogsSearchFilter/useSearchParser.ts b/frontend/src/container/LogsSearchFilter/useSearchParser.tsnew file mode 100644index 0000000000..0a66144370--- /dev/null+++ b/frontend/src/container/LogsSearchFilter/useSearchParser.ts@@ -0,0 +1,71 @@+import history from 'lib/history';+import { parseQuery, reverseParser } from 'lib/logql';+import { isEqual } from 'lodash-es';+import { useCallback, useEffect, useReducer, useState } from 'react';+import { useDispatch, useSelector } from 'react-redux';+import { AppState } from 'store/reducers';+import {+ SET_SEARCH_QUERY_PARSED_PAYLOAD,+ SET_SEARCH_QUERY_STRING,+} from 'types/actions/logs';+import ILogsReducer from 'types/reducer/logs';++export function useSearchParser() {+ const dispatch = useDispatch();+ const {+ searchFilter: { parsedQuery, queryString },+ } = useSelector<AppState, ILogsReducer>((store) => store.logs);++ const updateQueryString = useCallback(+ (updatedQueryString) => {+ history.push({+ pathname: history.location.pathname,+ search: updatedQueryString ? `?q=${updatedQueryString}` : '',+ });++ dispatch({+ type: SET_SEARCH_QUERY_STRING,+ payload: updatedQueryString,+ });+ const parsedQueryFromString = parseQuery(updatedQueryString);+ if (!isEqual(parsedQuery, parsedQueryFromString)) {+ dispatch({+ type: SET_SEARCH_QUERY_PARSED_PAYLOAD,+ payload: parsedQueryFromString,+ });+ }+ },+ [dispatch, parsedQuery],+ );++ useEffect(() => {+ updateQueryString(queryString);+ }, [queryString, updateQueryString]);++ const updateParsedQuery = useCallback(+ (updatedParsedPayload) => {+ dispatch({+ type: SET_SEARCH_QUERY_PARSED_PAYLOAD,+ payload: updatedParsedPayload,+ });+ const reversedParsedQuery = reverseParser(updatedParsedPayload);+ if (+ !isEqual(queryString, reversedParsedQuery) ||+ (queryString === '' && reversedParsedQuery === '')+ ) {+ dispatch({+ type: SET_SEARCH_QUERY_STRING,+ payload: reversedParsedQuery,+ });+ }+ },+ [dispatch, queryString],+ );++ return {+ queryString,+ parsedQuery,+ updateParsedQuery,+ updateQueryString,+ };+}diff --git a/frontend/src/container/LogsTable/index.tsx b/frontend/src/container/LogsTable/index.tsxnew file mode 100644index 0000000000..ee7024a53a--- /dev/null+++ b/frontend/src/container/LogsTable/index.tsx@@ -0,0 +1,86 @@+import { fetchEventSource } from '@microsoft/fetch-event-source';+import { Card, Typography } from 'antd';+import { LiveTail } from 'api/logs/livetail';+import LogItem from 'components/Logs/LogItem';+import Spinner from 'components/Spinner';+import { map } from 'lodash-es';+import React, { memo, useEffect, useRef } from 'react';+import { connect, useDispatch, useSelector } from 'react-redux';+import { bindActionCreators, Dispatch } from 'redux';+import { ThunkDispatch } from 'redux-thunk';+import { getLogs } from 'store/actions/logs/getLogs';+import { AppState } from 'store/reducers';+import AppActions from 'types/actions';+import { PUSH_LIVE_TAIL_EVENT } from 'types/actions/logs';+import { GlobalReducer } from 'types/reducer/globalTime';+import ILogsReducer from 'types/reducer/logs';++import { Container, Heading } from './styles';++function LogsTable({ getLogs }) {+ const {+ searchFilter: { queryString },+ logs,+ logLinesPerPage,+ idEnd,+ idStart,+ isLoading,+ liveTail,+ } = useSelector<AppState, ILogsReducer>((state) => state.logs);++ const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(+ (state) => state.globalTime,+ );++ useEffect(() => {+ if (liveTail === 'STOPPED')+ getLogs({+ q: queryString,+ limit: logLinesPerPage,+ orderBy: 'timestamp',+ order: 'desc',+ timestampStart: minTime,+ timestampEnd: maxTime,+ ...(idStart ? { idGt: idStart } : {}),+ ...(idEnd ? { idLt: idEnd } : {}),+ });+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [getLogs, idEnd, idStart, logLinesPerPage, maxTime, minTime, liveTail]);++ if (isLoading) {+ return <Spinner height={20} tip="Getting Logs" />;+ }+ return (+ <Container>+ <Heading>+ <Typography.Text+ style={{+ fontSize: '1rem',+ fontWeight: 400,+ }}+ >+ Event+ </Typography.Text>+ </Heading>+ {Array.isArray(logs) && logs.length > 0 ? (+ map(logs, (log) => <LogItem key={log.id} logData={log} />)+ ) : liveTail === 'PLAYING' ? (+ <span>Getting live logs...</span>+ ) : (+ <span>No log lines found</span>+ )}+ </Container>+ );+}++interface DispatchProps {+ getLogs: () => (dispatch: Dispatch<AppActions>) => void;+}++const mapDispatchToProps = (+ dispatch: ThunkDispatch<unknown, unknown, AppActions>,+): DispatchProps => ({+ getLogs: bindActionCreators(getLogs, dispatch),+});++export default connect(null, mapDispatchToProps)(memo(LogsTable));diff --git a/frontend/src/container/LogsTable/styles.ts b/frontend/src/container/LogsTable/styles.tsnew file mode 100644index 0000000000..49706cf706--- /dev/null+++ b/frontend/src/container/LogsTable/styles.ts@@ -0,0 +1,17 @@+import { grey } from '@ant-design/colors';+import { Card, Col } from 'antd';+import styled from 'styled-components';++export const Container = styled(Col)`+ overflow-x: hidden;+ width: 100%;+ margin-bottom: 1rem;+`;++export const Heading = styled(Card)`++ margin-bottom: 0.1rem;+ .ant-card-body {+ padding: 0.3rem 0.5rem;+ }+`;diff --git a/frontend/src/container/MetricsApplication/Tabs/Overview.tsx b/frontend/src/container/MetricsApplication/Tabs/Overview.tsxindex 7197887be1..3469765968 100644--- a/frontend/src/container/MetricsApplication/Tabs/Overview.tsx+++ b/frontend/src/container/MetricsApplication/Tabs/Overview.tsx@@ -49,8 +49,7 @@ function Application({ getWidget }: DashboardProps): JSX.Element {urlParams.set(METRICS_PAGE_QUERY_PARAM.endTime, tPlusOne.toString());history.replace(- `${- ROUTES.TRACE+ `${ROUTES.TRACE}?${urlParams.toString()}&selected={"serviceName":["${servicename}"]}&filterToFetchData=["duration","status","serviceName"]&spanAggregateCurrentPage=1&selectedTags=${selectedTraceTags}&&isFilterExclude={"serviceName":false}&userSelectedFilter={"status":["error","ok"],"serviceName":["${servicename}"]}&spanAggregateCurrentPage=1&spanAggregateOrder=ascend`,);};@@ -101,12 +100,17 @@ function Application({ getWidget }: DashboardProps): JSX.Element {urlParams.set(METRICS_PAGE_QUERY_PARAM.endTime, tPlusOne.toString());history.replace(- `${- ROUTES.TRACE+ `${ROUTES.TRACE}?${urlParams.toString()}?selected={"serviceName":["${servicename}"],"status":["error"]}&filterToFetchData=["duration","status","serviceName"]&spanAggregateCurrentPage=1&selectedTags=${selectedTraceTags}&isFilterExclude={"serviceName":false,"status":false}&userSelectedFilter={"serviceName":["${servicename}"],"status":["error"]}&spanAggregateCurrentPage=1&spanAggregateOrder=ascend`,);};-+ console.log(getWidget([+ {+ query: `max(sum(rate(signoz_calls_total{service_name="${servicename}", span_kind="SPAN_KIND_SERVER", status_code="STATUS_CODE_ERROR"${resourceAttributePromQLQuery}}[5m]) OR rate(signoz_calls_total{service_name="${servicename}", span_kind="SPAN_KIND_SERVER", http_status_code=~"5.."${resourceAttributePromQLQuery}}[5m]))*100/sum(rate(signoz_calls_total{service_name="${servicename}", span_kind="SPAN_KIND_SERVER"${resourceAttributePromQLQuery}}[5m]))) < 1000 OR vector(0)`,+ legend: 'Error Percentage',+ },+ ]))+ debugger;return (<><Row gutter={24}>diff --git a/frontend/src/container/SideNav/menuItems.ts b/frontend/src/container/SideNav/menuItems.tsindex 66a2a1fe77..d3e400dedf 100644--- a/frontend/src/container/SideNav/menuItems.ts+++ b/frontend/src/container/SideNav/menuItems.ts@@ -7,6 +7,7 @@ import {DashboardFilled,DeploymentUnitOutlined,LineChartOutlined,+ MenuOutlined,SettingOutlined,} from '@ant-design/icons';import ROUTES from 'constants/routes';@@ -18,10 +19,16 @@ const menus: SidebarMenu[] = [name: 'Services',},{- Icon: AlignLeftOutlined,+ Icon: MenuOutlined,to: ROUTES.TRACE,name: 'Traces',},+ {+ Icon: AlignLeftOutlined,+ to: ROUTES.LOGS,+ name: 'Logs',+ tags: ['Beta'],+ },{Icon: DashboardFilled,to: ROUTES.ALL_DASHBOARD,@@ -41,7 +48,6 @@ const menus: SidebarMenu[] = [to: ROUTES.SERVICE_MAP,name: 'Service Map',Icon: DeploymentUnitOutlined,- tags: ['Beta'],},{Icon: LineChartOutlined,diff --git a/frontend/src/container/TopNav/Breadcrumbs/index.tsx b/frontend/src/container/TopNav/Breadcrumbs/index.tsxindex c8d8bc9628..c4362cc32f 100644--- a/frontend/src/container/TopNav/Breadcrumbs/index.tsx+++ b/frontend/src/container/TopNav/Breadcrumbs/index.tsx@@ -18,6 +18,7 @@ const breadcrumbNameMap = {[ROUTES.ERROR_DETAIL]: 'Errors',[ROUTES.LIST_ALL_ALERT]: 'Alerts',[ROUTES.ALL_DASHBOARD]: 'Dashboard',+ [ROUTES.LOGS]: 'Logs'};function ShowBreadcrumbs(props: RouteComponentProps): JSX.Element {diff --git a/frontend/src/lib/__fixtures__/logql.ts b/frontend/src/lib/__fixtures__/logql.tsnew file mode 100644index 0000000000..b794973204--- /dev/null+++ b/frontend/src/lib/__fixtures__/logql.ts@@ -0,0 +1,208 @@+/* eslint no-useless-escape: 0 */++const logqlQueries = [+ {+ query: "OPERATION in ('bcd','xy\\'z') AND FULLTEXT contains 'helloxyz'", // Query with IN+ splitterQuery: [+ 'OPERATION',+ 'in',+ "('bcd','xy\\'z')",+ 'AND',+ 'FULLTEXT',+ 'contains',+ "'helloxyz'",+ ],+ parsedQuery: [+ { type: 'QUERY_KEY', value: 'OPERATION' },+ { type: 'QUERY_OPERATOR', value: 'in' },+ { type: 'QUERY_VALUE', value: ['bcd', "xy\\'z"] },+ { type: 'CONDITIONAL_OPERATOR', value: 'AND' },+ { type: 'QUERY_KEY', value: 'FULLTEXT' },+ { type: 'QUERY_OPERATOR', value: 'contains' },+ { type: 'QUERY_VALUE', value: "'helloxyz'" },+ ],+ },+ {+ query: "OPERATION in ('bcd') and FULLTEXT contains 'helloxyz'", // Query with IN+ splitterQuery: [+ 'OPERATION',+ 'in',+ "('bcd')",+ 'and',+ 'FULLTEXT',+ 'contains',+ "'helloxyz'",+ ],+ parsedQuery: [+ { type: 'QUERY_KEY', value: 'OPERATION' },+ { type: 'QUERY_OPERATOR', value: 'in' },+ { type: 'QUERY_VALUE', value: ['bcd'] },+ { type: 'CONDITIONAL_OPERATOR', value: 'and' },+ { type: 'QUERY_KEY', value: 'FULLTEXT' },+ { type: 'QUERY_OPERATOR', value: 'contains' },+ { type: 'QUERY_VALUE', value: "'helloxyz'" },+ ],+ },+ {+ query: "OPERATION in ('bcd','xyz') AND FULLTEXT contains 'helloxyz'", // Query with IN+ splitterQuery: [+ 'OPERATION',+ 'in',+ "('bcd','xyz')",+ 'AND',+ 'FULLTEXT',+ 'contains',+ "'helloxyz'",+ ],+ parsedQuery: [+ { type: 'QUERY_KEY', value: 'OPERATION' },+ { type: 'QUERY_OPERATOR', value: 'in' },+ { type: 'QUERY_VALUE', value: ['bcd', 'xyz'] },+ { type: 'CONDITIONAL_OPERATOR', value: 'AND' },+ { type: 'QUERY_KEY', value: 'FULLTEXT' },+ { type: 'QUERY_OPERATOR', value: 'contains' },+ { type: 'QUERY_VALUE', value: "'helloxyz'" },+ ],+ },+ {+ query: "status gte 200 AND FULLTEXT contains 'helloxyz'",+ splitterQuery: [+ 'status',+ 'gte',+ '200',+ 'AND',+ 'FULLTEXT',+ 'contains',+ "'helloxyz'",+ ],+ parsedQuery: [+ { type: 'QUERY_KEY', value: 'status' },+ { type: 'QUERY_OPERATOR', value: 'gte' },+ { type: 'QUERY_VALUE', value: '200' },+ { type: 'CONDITIONAL_OPERATOR', value: 'AND' },+ { type: 'QUERY_KEY', value: 'FULLTEXT' },+ { type: 'QUERY_OPERATOR', value: 'contains' },+ { type: 'QUERY_VALUE', value: "'helloxyz'" },+ ],+ },+ {+ query: "service IN ('Hello (\\'World')", // Query with quotes and brackets+ splitterQuery: ['service', 'IN', "('Hello (\\'World')"],+ parsedQuery: [+ { type: 'QUERY_KEY', value: 'service' },+ { type: 'QUERY_OPERATOR', value: 'IN' },+ { type: 'QUERY_VALUE', value: ["Hello (\\'World"] },+ ],+ },+ {+ query: "service IN ('Hello (\\'World') AND FULLTEXT contains 'ola'", // Query with full text as key pair+ splitterQuery: [+ 'service',+ 'IN',+ "('Hello (\\'World')",+ 'AND',+ 'FULLTEXT',+ 'contains',+ "'ola'",+ ],+ parsedQuery: [+ { type: 'QUERY_KEY', value: 'service' },+ { type: 'QUERY_OPERATOR', value: 'IN' },+ { type: 'QUERY_VALUE', value: ["Hello (\\'World"] },+ { type: 'CONDITIONAL_OPERATOR', value: 'AND' },+ { type: 'QUERY_KEY', value: 'FULLTEXT' },+ { type: 'QUERY_OPERATOR', value: 'contains' },+ { type: 'QUERY_VALUE', value: "'ola'" },+ ],+ },+ {+ query: 'id lt 100 and id gt 50 and code lte 500 and code gte 400', // Query with numbers+ splitterQuery: [+ 'id',+ 'lt',+ '100',+ 'and',+ 'id',+ 'gt',+ '50',+ 'and',+ 'code',+ 'lte',+ '500',+ 'and',+ 'code',+ 'gte',+ '400',+ ],+ parsedQuery: [+ { type: 'QUERY_KEY', value: 'id' },+ { type: 'QUERY_OPERATOR', value: 'lt' },+ { type: 'QUERY_VALUE', value: '100' },+ { type: 'CONDITIONAL_OPERATOR', value: 'and' },+ { type: 'QUERY_KEY', value: 'id' },+ { type: 'QUERY_OPERATOR', value: 'gt' },+ { type: 'QUERY_VALUE', value: '50' },+ { type: 'CONDITIONAL_OPERATOR', value: 'and' },+ { type: 'QUERY_KEY', value: 'code' },+ { type: 'QUERY_OPERATOR', value: 'lte' },+ { type: 'QUERY_VALUE', value: '500' },+ { type: 'CONDITIONAL_OPERATOR', value: 'and' },+ { type: 'QUERY_KEY', value: 'code' },+ { type: 'QUERY_OPERATOR', value: 'gte' },+ { type: 'QUERY_VALUE', value: '400' },+ ],+ },+ {+ query: 'FULLTEXT contains \'Hello, "World"\'', // Full text with Quotes+ splitterQuery: ['FULLTEXT', 'contains', `'Hello, "World"'`],+ parsedQuery: [+ { type: 'QUERY_KEY', value: 'FULLTEXT' },+ { type: 'QUERY_OPERATOR', value: 'contains' },+ { type: 'QUERY_VALUE', value: `'Hello, "World"'` },+ ],+ },++ {+ query: "service NIN ('name > 100') AND length gt 100", // Characters inside string+ splitterQuery: [+ 'service',+ 'NIN',+ "('name > 100')",+ 'AND',+ 'length',+ 'gt',+ '100',+ ],+ parsedQuery: [+ { type: 'QUERY_KEY', value: 'service' },+ { type: 'QUERY_OPERATOR', value: 'NIN' },+ { type: 'QUERY_VALUE', value: ['name > 100'] },+ { type: 'CONDITIONAL_OPERATOR', value: 'AND' },+ { type: 'QUERY_KEY', value: 'length' },+ { type: 'QUERY_OPERATOR', value: 'gt' },+ { type: 'QUERY_VALUE', value: '100' },+ ],+ },++ // Template+ {+ query: '',+ splitterQuery: [],+ parsedQuery: [],+ },+];++const specialLogQLQueries = [+ {+ query: 'key IN 22', // Fulltext+ splitterQuery: ['key', 'IN', '22'],+ parsedQuery: [+ { type: 'QUERY_KEY', value: 'FULLTEXT' },+ { type: 'QUERY_OPERATOR', value: 'CONTAINS' },+ { type: 'QUERY_VALUE', value: 'key IN 22' },+ ],+ reverseParsed: "FULLTEXT CONTAINS 'key IN 22'",+ },+];++export { logqlQueries, specialLogQLQueries };diff --git a/frontend/src/lib/__tests__/logql/parser.test.ts b/frontend/src/lib/__tests__/logql/parser.test.tsnew file mode 100644index 0000000000..e5e813d921--- /dev/null+++ b/frontend/src/lib/__tests__/logql/parser.test.ts@@ -0,0 +1,15 @@+import { logqlQueries } from 'lib/__fixtures__/logql';+import parser from 'lib/logql/parser';++describe('lib/logql/parser', () => {+ test('parse valid queries', () => {+ logqlQueries.forEach((queryObject) => {+ try {+ parser(queryObject.query);+ } catch (e) {+ console.log(e);+ }+ expect(parser(queryObject.query)).toEqual(queryObject.parsedQuery);+ });+ });+});diff --git a/frontend/src/lib/__tests__/logql/reverseParser.test.ts b/frontend/src/lib/__tests__/logql/reverseParser.test.tsnew file mode 100644index 0000000000..e4b57d5b89--- /dev/null+++ b/frontend/src/lib/__tests__/logql/reverseParser.test.ts@@ -0,0 +1,14 @@+import { logqlQueries } from 'lib/__fixtures__/logql';+import reverseParser from 'lib/logql/reverseParser';++describe('lib/logql/reverseParser', () => {+ test('reverse parse valid queries', () => {+ logqlQueries.forEach((queryObject) => {+ try {+ expect(reverseParser(queryObject.parsedQuery)).toEqual(queryObject.query);+ } catch (e) {+ console.log(e);+ }+ });+ });+});diff --git a/frontend/src/lib/__tests__/logql/splitter.test.ts b/frontend/src/lib/__tests__/logql/splitter.test.tsnew file mode 100644index 0000000000..360004aba8--- /dev/null+++ b/frontend/src/lib/__tests__/logql/splitter.test.ts@@ -0,0 +1,9 @@+import splitter from 'lib/logql/splitter';+import { logqlQueries } from 'lib/__fixtures__/logql';+describe('lib/logql/splitter', () => {+ test('splitter valid quereies', () => {+ logqlQueries.forEach((queryObject) => {+ expect(splitter(queryObject.query)).toEqual(queryObject.splitterQuery);+ });+ });+});diff --git a/frontend/src/lib/logql/errors/ConvertToFullText.ts b/frontend/src/lib/logql/errors/ConvertToFullText.tsnew file mode 100644index 0000000000..c9093ddcbb--- /dev/null+++ b/frontend/src/lib/logql/errors/ConvertToFullText.ts@@ -0,0 +1,7 @@+export class ErrorConvertToFullText extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'ErrorConvertToFullText';+ Object.setPrototypeOf(this, ErrorConvertToFullText.prototype);+ }+}diff --git a/frontend/src/lib/logql/errors/InvalidQueryPair.ts b/frontend/src/lib/logql/errors/InvalidQueryPair.tsnew file mode 100644index 0000000000..c203b09ba8--- /dev/null+++ b/frontend/src/lib/logql/errors/InvalidQueryPair.ts@@ -0,0 +1,7 @@+export class ErrorInvalidQueryPair extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'ErrorInvalidQueryPair';+ Object.setPrototypeOf(this, ErrorInvalidQueryPair.prototype);+ }+}diff --git a/frontend/src/lib/logql/errors/index.ts b/frontend/src/lib/logql/errors/index.tsnew file mode 100644index 0000000000..f23e2a0734--- /dev/null+++ b/frontend/src/lib/logql/errors/index.ts@@ -0,0 +1,2 @@+export * from './ConvertToFullText';+export * from './InvalidQueryPair';diff --git a/frontend/src/lib/logql/index.ts b/frontend/src/lib/logql/index.tsnew file mode 100644index 0000000000..d557c993f8--- /dev/null+++ b/frontend/src/lib/logql/index.ts@@ -0,0 +1,4 @@+export * from './parser';+export * from './reverseParser';+export * from './splitter';+export * from './tokens';diff --git a/frontend/src/lib/logql/parser.ts b/frontend/src/lib/logql/parser.tsnew file mode 100644index 0000000000..af92bcb90b--- /dev/null+++ b/frontend/src/lib/logql/parser.ts@@ -0,0 +1,149 @@+// @ts-nocheck+import splitter from 'lib/logql/splitter';+import {+ ConditionalOperators,+ QueryOperatorsMultiVal,+ QueryOperatorsSingleVal,+ QueryTypes,+} from 'lib/logql/tokens';+import {+ ErrorConvertToFullText,+ ErrorInvalidQueryPair,+} from 'lib/logql/errors';++const validateMultiValue = (queryToken: string): boolean => {+ const queryValues = [];+ let start;+ let isQuoteStart = false;+ if (queryToken[0] === '(' && queryToken[queryToken.length - 1] === ')') {+ for (let idx = 1; idx < queryToken.length - 1; idx += 1) {+ if (queryToken[idx] === "'") {+ if (queryToken[idx - 1] === '\\') {+ // skip+ } else if (isQuoteStart) {+ isQuoteStart = false;+ queryValues.push(queryToken.slice(start, idx));+ } else {+ isQuoteStart = true;+ start = idx + 1;+ }+ }+ }+ } else {+ return false;+ }+ return queryValues;+};+export const parseQuery = (queryString) => {+ let parsedRaw = [];+ const generateQuery = (queryToken) => {+ const prevToken = parsedRaw[parsedRaw.length - 1];++ // Is a QUERY_KEY+ if (+ prevToken === undefined ||+ prevToken.type === QueryTypes.CONDITIONAL_OPERATOR+ ) {+ parsedRaw.push({+ type: QueryTypes.QUERY_KEY,+ value: queryToken,+ });+ }+ // Is a QUERY_OPERATOR+ else if (prevToken && prevToken.type === QueryTypes.QUERY_KEY) {+ if (+ Object.values({+ ...QueryOperatorsMultiVal,+ ...QueryOperatorsSingleVal,+ }).find((op) => op.toLowerCase() === queryToken.toLowerCase())+ )+ parsedRaw.push({+ type: QueryTypes.QUERY_OPERATOR,+ value: queryToken,+ });+ else {+ throw new ErrorInvalidQueryPair(+ 'Expected conditional operator received',+ queryToken,+ );+ }+ }+ // Is a QUERY_VALUE+ else if (prevToken && prevToken.type === QueryTypes.QUERY_OPERATOR) {+ // Check for multi value+ let value = queryToken;+ // if (+ // typeof queryToken === 'string' &&+ // queryToken.length >= 2 &&+ // queryToken[0] === "'" &&+ // queryToken[queryToken.length - 1] === "'"+ // ) {+ // value = queryToken.slice(1, queryToken.length - 1);+ // }+ if (+ Object.values(QueryOperatorsMultiVal).some(+ (operator) => operator.toLowerCase() === prevToken.value.toLowerCase(),+ )+ ) {+ value = validateMultiValue(queryToken);+ if (value === false) {+ throw new ErrorConvertToFullText();+ }+ }++ parsedRaw.push({+ type: QueryTypes.QUERY_VALUE,+ value,+ });+ } else if (prevToken && prevToken.type === QueryTypes.QUERY_VALUE) {+ if (+ Object.values(ConditionalOperators).find(+ (op) => op.toLowerCase() === queryToken.toLowerCase(),+ )+ )+ parsedRaw.push({+ type: QueryTypes.CONDITIONAL_OPERATOR,+ value: queryToken,+ });+ else {+ throw new ErrorInvalidQueryPair(+ 'Expected conditional operator received',+ queryToken,+ );+ }+ } else {+ // Not a Key+ }+ };++ try {+ const spaceSplittedQUery = splitter(queryString);+ spaceSplittedQUery.forEach((q) => {+ generateQuery(q);+ });+ } catch (e: Error) {+ if (e instanceof ErrorInvalidQueryPair) {+ //+ } else if (e instanceof ErrorConvertToFullText) {+ parsedRaw = [+ {+ type: QueryTypes.QUERY_KEY,+ value: 'FULLTEXT',+ },+ {+ type: QueryTypes.QUERY_OPERATOR,+ value: 'CONTAINS',+ },+ {+ type: QueryTypes.QUERY_VALUE,+ value: String.raw`${queryString}`,+ },+ ];+ }+ }++ // console.log(parsedRaw);+ return parsedRaw;+};++export default parseQuery;diff --git a/frontend/src/lib/logql/reverseParser.ts b/frontend/src/lib/logql/reverseParser.tsnew file mode 100644index 0000000000..d3ccf6824c--- /dev/null+++ b/frontend/src/lib/logql/reverseParser.ts@@ -0,0 +1,23 @@+// @ts-nocheck++export const reverseParser = (+ parserQueryArr: { type: string; value: any }[] = [],+) => {+ let queryString = '';+ parserQueryArr.forEach((query) => {+ if (queryString) {+ queryString += ' ';+ }++ if (Array.isArray(query.value) && query.value.length > 0) {+ queryString += `(${query.value.map((val) => `'${val}'`).join(',')})`;+ } else {+ queryString += query.value;+ }+ });++ // console.log(queryString);+ return queryString;+};++export default reverseParser;diff --git a/frontend/src/lib/logql/splitter.ts b/frontend/src/lib/logql/splitter.tsnew file mode 100644index 0000000000..c43f566399--- /dev/null+++ b/frontend/src/lib/logql/splitter.ts@@ -0,0 +1,55 @@+// @ts-nocheck++export const splitter = (queryString) => {+ const splittedParts = [];+ let start = 0;+ let isBracketStart = false;+ let isQuoteStart = false;++ const pushPart = (idx) => {+ splittedParts.push(queryString.slice(start, idx));+ start = idx + 1;+ };+ for (let idx = 0; idx < queryString.length; idx += 1) {+ const currentChar = queryString[idx];++ // if (start === null) {+ // start = idx;+ // }++ if (currentChar === ' ') {+ if (!isBracketStart && !isQuoteStart) {+ pushPart(idx);+ }+ } else if (currentChar === '(') {+ isBracketStart = true;+ } else if (currentChar === ')') {+ if (queryString[idx - 1] !== '\\') {+ pushPart(idx + 1);+ isBracketStart = false;+ }+ if (isQuoteStart) {+ isQuoteStart = false;+ }+ } else if (currentChar === "'") {+ if (isQuoteStart) {+ if (queryString[idx - 1] !== '\\' && !isBracketStart) {+ pushPart(idx + 1);+ isQuoteStart = false;+ }+ } else {+ isQuoteStart = true;+ }+ }+ }++ // Process remaining part+ if (start < queryString.length) {+ pushPart(queryString.length);+ }++ // console.log(splittedParts.filter(Boolean));+ return splittedParts.map((s) => String.raw`${s}`).filter(Boolean);+};++export default splitter;diff --git a/frontend/src/lib/logql/tokens.ts b/frontend/src/lib/logql/tokens.tsnew file mode 100644index 0000000000..1c98c8c96e--- /dev/null+++ b/frontend/src/lib/logql/tokens.ts@@ -0,0 +1,26 @@+export const QueryOperatorsSingleVal = {+ GTE: 'GTE',+ GT: 'GT',+ LTE: 'LTE',+ LT: 'LT',+ CONTAINS: 'CONTAINS',+ NCONTAINS: 'NCONTAINS',+};++export const QueryOperatorsMultiVal = {+ IN: 'IN',+ NIN: 'NIN',+};++export const ConditionalOperators = {+ AND: 'AND',+ OR: 'OR',+};+++export const QueryTypes = {+ QUERY_KEY: 'QUERY_KEY',+ QUERY_OPERATOR: 'QUERY_OPERATOR',+ QUERY_VALUE: 'QUERY_VALUE',+ CONDITIONAL_OPERATOR: 'CONDITIONAL_OPERATOR',+};diff --git a/frontend/src/lib/logql/types.ts b/frontend/src/lib/logql/types.tsnew file mode 100644index 0000000000..6145fd4acb--- /dev/null+++ b/frontend/src/lib/logql/types.ts@@ -0,0 +1,4 @@+export interface ILogQLParsedQueryItem {+ type: string;+ value: string | string[];+}diff --git a/frontend/src/lib/logs/fieldSearch.ts b/frontend/src/lib/logs/fieldSearch.tsnew file mode 100644index 0000000000..669a60c6c7--- /dev/null+++ b/frontend/src/lib/logs/fieldSearch.ts@@ -0,0 +1,6 @@+export const fieldSearchFilter = (searchSpace = '', currentValue = '') => {+ if (!currentValue || !searchSpace) {+ return true;+ }+ return searchSpace.toLowerCase().indexOf(currentValue.toLowerCase()) !== -1;+};diff --git a/frontend/src/lib/logs/flatLogData.ts b/frontend/src/lib/logs/flatLogData.tsnew file mode 100644index 0000000000..b8dc79a816--- /dev/null+++ b/frontend/src/lib/logs/flatLogData.ts@@ -0,0 +1,16 @@+import { ILog } from 'types/api/logs/log';++export function FlatLogData(log: ILog): Record<string, never> {+ let flattenLogObject: Record<string, never> = {};++ Object.keys(log).forEach((key: string) => {+ if (typeof log[key] !== 'object') {+ flattenLogObject[key] = log[key];+ } else {+ Object.keys(log[key]).forEach((childKey) => {+ flattenLogObject[childKey] = log[key][childKey]+ });+ }+ });+ return flattenLogObject;+}diff --git a/frontend/src/lib/logs/generateFilterQuery.ts b/frontend/src/lib/logs/generateFilterQuery.tsnew file mode 100644index 0000000000..31596e8c74--- /dev/null+++ b/frontend/src/lib/logs/generateFilterQuery.ts@@ -0,0 +1,10 @@+export const generateFilterQuery = ({ fieldKey, fieldValue, type }) => {+ let generatedQueryString = `${fieldKey} ${type} `;+ if (typeof fieldValue === 'number') {+ generatedQueryString += `(${fieldValue})`;+ } else {+ generatedQueryString += `('${fieldValue}')`;+ }++ return generatedQueryString;+};diff --git a/frontend/src/pages/Logs/index.tsx b/frontend/src/pages/Logs/index.tsxnew file mode 100644index 0000000000..bd2a95806b--- /dev/null+++ b/frontend/src/pages/Logs/index.tsx@@ -0,0 +1,8 @@+import Logs from 'container/Logs';+import React from 'react';++function LogsHome() {+ return <Logs />;+}++export default LogsHome;diff --git a/frontend/src/store/actions/logs/addToSelectedField.ts b/frontend/src/store/actions/logs/addToSelectedField.tsnew file mode 100644index 0000000000..2726639e43--- /dev/null+++ b/frontend/src/store/actions/logs/addToSelectedField.ts@@ -0,0 +1,16 @@+import GetSearchFields from 'api/logs/GetSearchFields';+import { Dispatch } from 'redux';+import AppActions from 'types/actions';+import { GET_FIELDS, SET_FIELDS } from 'types/actions/logs';+import { TraceReducer } from 'types/reducer/trace';++export const AddToSelectedField = (): ((dispatch: Dispatch<AppActions>) => void) => {+ return async (dispatch): void => {+ const response = await GetSearchFields();++ dispatch({+ type: SET_FIELDS,+ payload: response.payload,+ });+ };+};diff --git a/frontend/src/store/actions/logs/getFields.ts b/frontend/src/store/actions/logs/getFields.tsnew file mode 100644index 0000000000..9627a6cb48--- /dev/null+++ b/frontend/src/store/actions/logs/getFields.ts@@ -0,0 +1,24 @@+import GetSearchFields from 'api/logs/GetSearchFields';+import { Dispatch } from 'redux';+import AppActions from 'types/actions';+import { GET_FIELDS, SET_FIELDS } from 'types/actions/logs';+import { TraceReducer } from 'types/reducer/trace';++const IGNORED_SELECTED_FIELDS = ['timestamp'];++export const GetLogsFields = (): ((dispatch: Dispatch<AppActions>) => void) => {+ return async (dispatch): void => {+ const response = await GetSearchFields();+ if (response.payload) {+ dispatch({+ type: SET_FIELDS,+ payload: {+ interesting: response.payload.interesting,+ selected: response.payload.selected.filter(+ (field) => !IGNORED_SELECTED_FIELDS.includes(field.name),+ ),+ },+ });+ }+ };+};diff --git a/frontend/src/store/actions/logs/getLogs.ts b/frontend/src/store/actions/logs/getLogs.tsnew file mode 100644index 0000000000..bcb87f56cc--- /dev/null+++ b/frontend/src/store/actions/logs/getLogs.ts@@ -0,0 +1,31 @@+import GetLogs from 'api/logs/GetLogs';+import { Dispatch } from 'redux';+import AppActions from 'types/actions';+import { SET_LOADING, SET_LOGS } from 'types/actions/logs';++export const getLogs = (props): ((dispatch: Dispatch<AppActions>) => void) => {+ return async (dispatch): void => {+ dispatch({+ type: SET_LOADING,+ payload: true,+ });++ const response = await GetLogs(props);++ if (response.payload)+ dispatch({+ type: SET_LOGS,+ payload: response.payload,+ });+ else+ dispatch({+ type: SET_LOGS,+ payload: [],+ });++ dispatch({+ type: SET_LOADING,+ payload: false,+ });+ };+};diff --git a/frontend/src/store/actions/logs/getLogsAggregate.ts b/frontend/src/store/actions/logs/getLogsAggregate.tsnew file mode 100644index 0000000000..4ce63ff0e3--- /dev/null+++ b/frontend/src/store/actions/logs/getLogsAggregate.ts@@ -0,0 +1,46 @@+import GetLogs from 'api/logs/GetLogs';+import GetLogsAggregate from 'api/logs/GetLogsAggregate';+import { Dispatch } from 'redux';+import AppActions from 'types/actions';+import {+ SET_LOADING,+ SET_LOADING_AGGREGATE,+ SET_LOGS,+ SET_LOGS_AGGREGATE_SERIES,+} from 'types/actions/logs';+import { ILogsAggregate } from 'types/api/logs/logAggregate';++export const getLogsAggregate = (+ props,+): ((dispatch: Dispatch<AppActions>) => void) => {+ return async (dispatch): void => {+ dispatch({+ type: SET_LOADING_AGGREGATE,+ payload: true,+ });++ const response = await GetLogsAggregate(props);+ if (response.payload) {+ const convertedArray: ILogsAggregate[] = Object.values(response.payload).map(+ (data) => {+ return { ...data, time: new Date(data.timestamp / 1e6) };+ },+ );++ dispatch({+ type: SET_LOGS_AGGREGATE_SERIES,+ payload: convertedArray,+ });+ } else {+ dispatch({+ type: SET_LOGS_AGGREGATE_SERIES,+ payload: [],+ });+ }++ dispatch({+ type: SET_LOADING_AGGREGATE,+ payload: false,+ });+ };+};diff --git a/frontend/src/store/reducers/index.ts b/frontend/src/store/reducers/index.tsindex 690464b215..d0e99315bb 100644--- a/frontend/src/store/reducers/index.ts+++ b/frontend/src/store/reducers/index.ts@@ -3,6 +3,7 @@ import { combineReducers } from 'redux';import appReducer from './app';import dashboardReducer from './dashboard';import globalTimeReducer from './global';+import LogsReducer from './logs';import metricsReducers from './metric';import { ServiceMapReducer } from './serviceMap';import traceReducer from './trace';@@ -16,6 +17,7 @@ const reducers = combineReducers({dashboards: dashboardReducer,app: appReducer,metrics: metricsReducers,+ logs: LogsReducer,});export type AppState = ReturnType<typeof reducers>;diff --git a/frontend/src/store/reducers/logs.ts b/frontend/src/store/reducers/logs.tsnew file mode 100644index 0000000000..4218334ebf--- /dev/null+++ b/frontend/src/store/reducers/logs.ts@@ -0,0 +1,233 @@+import { parseQuery } from 'lib/logql';+import {+ ADD_SEARCH_FIELD_QUERY_STRING,+ FLUSH_LOGS,+ GET_FIELDS,+ GET_NEXT_LOG_LINES,+ GET_PREVIOUS_LOG_LINES,+ LogsActions,+ PUSH_LIVE_TAIL_EVENT,+ RESET_ID_START_AND_END,+ SET_DETAILED_LOG_DATA,+ SET_FIELDS,+ SET_LIVE_TAIL_START_TIME,+ SET_LOADING,+ SET_LOADING_AGGREGATE,+ SET_LOG_LINES_PER_PAGE,+ SET_LOGS,+ SET_LOGS_AGGREGATE_SERIES,+ SET_SEARCH_QUERY_PARSED_PAYLOAD,+ SET_SEARCH_QUERY_STRING,+ STOP_LIVE_TAIL,+ TOGGLE_LIVE_TAIL,+} from 'types/actions/logs';+import ILogsReducer from 'types/reducer/logs';++const initialState: ILogsReducer = {+ fields: {+ interesting: [],+ selected: [],+ },+ searchFilter: {+ queryString: '',+ parsedQuery: [],+ },+ logs: [],+ logLinesPerPage: 25,+ idEnd: '',+ idStart: '',+ isLoading: false,+ isLoadingAggregate: false,+ logsAggregate: [],+ detailedLog: null,+ liveTail: 'STOPPED',+ liveTailStartRange: 15,+ // detailedLog: {+ // timestamp: 1659360016955270100,+ // id: '2CkBCauK8m3nkyKR19YhCw6WfvD',+ // traceId: '',+ // spanId: '',+ // traceFlags: 0,+ // severityText: '',+ // severityNumber: 0,+ // body:+ // '49.207.215.17 - - [01/Aug/2022:13:20:16 +0000] "OPTIONS /api/v1/logs/fields HTTP/1.1" 200 23 "http://localhost:3301/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36" "-"\n',+ // resourcesString: {+ // source: 'docker',+ // },+ // attributesString: {+ // container_id:+ // 'b3c6808322609f7671c18a09515d9c84909c873471b560da65c1afe0dfd933ea',+ // log_file_path:+ // '/var/lib/docker/containers/b3c6808322609f7671c18a09515d9c84909c873471b560da65c1afe0dfd933ea/b3c6808322609f7671c18a09515d9c84909c873471b560da65c1afe0dfd933ea-json.log',+ // stream: 'stdout',+ // time: '2022-08-01T13:20:16.955270245Z',+ // },+ // attributesInt: {},+ // attributesFloat: {},+ // },+};++export const LogsReducer = (+ state = initialState,+ action: LogsActions,+): ILogsReducer => {+ switch (action.type) {+ case SET_LOADING: {+ return {+ ...state,+ isLoading: action.payload,+ };+ }++ case SET_LOADING_AGGREGATE: {+ return {+ ...state,+ isLoadingAggregate: action.payload,+ };+ }++ case GET_FIELDS:+ return {+ ...state,+ };++ case SET_FIELDS: {+ const newFields = action.payload;++ return {+ ...state,+ fields: newFields,+ };+ }++ case SET_SEARCH_QUERY_STRING: {+ return {+ ...state,+ searchFilter: {+ ...state.searchFilter,+ queryString: action.payload,+ },+ };+ }++ case SET_SEARCH_QUERY_PARSED_PAYLOAD: {+ return {+ ...state,+ searchFilter: {+ ...state.searchFilter,+ parsedQuery: action.payload,+ },+ };+ }++ case ADD_SEARCH_FIELD_QUERY_STRING: {+ const updatedQueryString =+ state.searchFilter.queryString ++ (state.searchFilter.queryString.length > 0 ? ' and ' : '') ++ action.payload;++ const updatedParsedQuery = parseQuery(updatedQueryString);+ return {+ ...state,+ searchFilter: {+ ...state.searchFilter,+ queryString: updatedQueryString,+ parsedQuery: updatedParsedQuery,+ },+ };+ }++ case SET_LOGS: {+ const logsData = action.payload;+ return {+ ...state,+ logs: logsData,+ };+ }+ case SET_LOG_LINES_PER_PAGE: {+ return {+ ...state,+ logLinesPerPage: action.payload,+ };+ }++ case GET_PREVIOUS_LOG_LINES: {+ const idStart = state.logs.length > 0 ? state.logs[0].id : '';+ return {+ ...state,+ idStart,+ idEnd: '',+ };+ }++ case GET_NEXT_LOG_LINES: {+ const idEnd =+ state.logs.length > 0 ? state.logs[state.logs.length - 1].id : '';+ return {+ ...state,+ idStart: '',+ idEnd,+ };+ }++ case RESET_ID_START_AND_END: {+ return {+ ...state,+ idEnd: '',+ idStart: '',+ };+ }++ case SET_LOGS_AGGREGATE_SERIES: {+ return {+ ...state,+ logsAggregate: action.payload,+ };+ }++ case SET_DETAILED_LOG_DATA: {+ return {+ ...state,+ detailedLog: action.payload,+ };+ }++ case TOGGLE_LIVE_TAIL: {+ return {+ ...state,+ liveTail: action.payload,+ };+ }+ case STOP_LIVE_TAIL: {+ return {+ ...state,+ logs: [],+ liveTail: 'STOPPED',+ };+ }+ case PUSH_LIVE_TAIL_EVENT: {+ return {+ ...state,+ logs: action.payload.concat(state.logs).slice(0, 100),+ };+ }+ case SET_LIVE_TAIL_START_TIME: {+ return {+ ...state,+ liveTailStartRange: action.payload,+ };+ }+ case FLUSH_LOGS: {+ return {+ ...state,+ logs: [],+ };+ }++ default:+ return state;+ }+};++export default LogsReducer;diff --git a/frontend/src/types/actions/index.ts b/frontend/src/types/actions/index.tsindex da5a26f5fd..5d15b0c150 100644--- a/frontend/src/types/actions/index.ts+++ b/frontend/src/types/actions/index.ts@@ -1,6 +1,7 @@import { AppAction } from './app';import { DashboardActions } from './dashboard';import { GlobalTimeAction } from './globalTime';+import { LogsActions } from './logs';import { MetricsActions } from './metrics';import { TraceActions } from './trace';@@ -9,6 +10,7 @@ type AppActions =| AppAction| GlobalTimeAction| MetricsActions- | TraceActions;+ | TraceActions+ | LogsActions;export default AppActions;diff --git a/frontend/src/types/actions/logs.ts b/frontend/src/types/actions/logs.tsnew file mode 100644index 0000000000..12d5835bd2--- /dev/null+++ b/frontend/src/types/actions/logs.ts@@ -0,0 +1,183 @@+// import { DBOverView } from 'types/api/metrics/getDBOverview';+// import { ExternalAverageDuration } from 'types/api/metrics/getExternalAverageDuration';+// import { ExternalError } from 'types/api/metrics/getExternalError';+// import { ExternalService } from 'types/api/metrics/getExternalService';+// import { IResourceAttributeQuery } from 'container/MetricsApplication/ResourceAttributesFilter/types';+// import { ServicesList } from 'types/api/metrics/getService';+// import { ServiceOverview } from 'types/api/metrics/getServiceOverview';+// import { TopEndPoints } from 'types/api/metrics/getTopEndPoints';++import { ILogQLParsedQueryItem } from 'lib/logql/types';+import { IFieldMoveToSelected, IFields } from 'types/api/logs/fields';+import { TLogsLiveTailState } from 'types/api/logs/liveTail';+import { ILog } from 'types/api/logs/log';+import { ILogsAggregate } from 'types/api/logs/logAggregate';++// export const GET_SERVICE_LIST_SUCCESS = 'GET_SERVICE_LIST_SUCCESS';+// export const GET_SERVICE_LIST_LOADING_START = 'GET_SERVICE_LIST_LOADING_START';+// export const GET_SERVICE_LIST_ERROR = 'GET_SERVICE_LIST_ERROR';+// export const GET_INITIAL_APPLICATION_LOADING =+// 'GET_INITIAL_APPLICATION_LOADING';+// export const GET_INITIAL_APPLICATION_ERROR = 'GET_INITIAL_APPLICATION_ERROR';+// export const GET_INTIAL_APPLICATION_DATA = 'GET_INTIAL_APPLICATION_DATA';+// export const RESET_INITIAL_APPLICATION_DATA = 'RESET_INITIAL_APPLICATION_DATA';+export const GET_FIELDS = 'LOGS_GET_FIELDS';+export const SET_FIELDS = 'LOGS_SET_FIELDS';+export const SET_SEARCH_QUERY_STRING = 'LOGS_SET_SEARCH_QUERY_STRING';+export const SET_SEARCH_QUERY_PARSED_PAYLOAD =+ 'LOGS_SET_SEARCH_QUERY_PARSED_PAYLOAD';+export const ADD_SEARCH_FIELD_QUERY_STRING =+ 'LOGS_ADD_SEARCH_FIELD_QUERY_STRING';+export const ADD_TO_SELECTED_FIELD = 'LOGS_ADD_TO_SELECTED_FIELD';+export const SET_LOGS = 'LOGS_SET_LOGS';+export const SET_LOG_LINES_PER_PAGE = 'LOGS_SET_LOG_LINES_PER_PAGE';+export const GET_NEXT_LOG_LINES = 'LOGS_GET_NEXT_LOG_LINES';+export const GET_PREVIOUS_LOG_LINES = 'LOGS_GET_PREVIOUS_LOG_LINES';+export const RESET_ID_START_AND_END = 'LOGS_RESET_ID_START_AND_END';+export const SET_LOADING = 'LOGS_SET_LOADING';+export const SET_LOADING_AGGREGATE = 'LOGS_SET_LOADING_AGGREGATE';+export const SET_LOGS_AGGREGATE_SERIES = 'LOGS_SET_LOGS_AGGREGATE_SERIES';+export const SET_DETAILED_LOG_DATA = 'LOGS_SET_DETAILED_LOG_DATA';+export const TOGGLE_LIVE_TAIL = 'LOGS_TOGGLE_LIVE_TAIL';+export const PUSH_LIVE_TAIL_EVENT = 'LOGS_PUSH_LIVE_TAIL_EVENT';+export const STOP_LIVE_TAIL = 'LOGS_STOP_LIVE_TAIL';+export const FLUSH_LOGS = 'LOGS_FLUSH_LOGS';+export const SET_LIVE_TAIL_START_TIME = 'LOGS_SET_LIVE_TAIL_START_TIME';+export interface GetFields {+ type: typeof GET_FIELDS;+}++export interface SetFields {+ type: typeof SET_FIELDS;+ payload: IFields;+}+export interface SetSearchQueryString {+ type: typeof SET_SEARCH_QUERY_STRING;+ payload: string;+}++export interface SetSearchQueryParsedPayload {+ type: typeof SET_SEARCH_QUERY_PARSED_PAYLOAD;+ payload: ILogQLParsedQueryItem[];+}+export interface AddSearchFieldQueryString {+ type: typeof ADD_SEARCH_FIELD_QUERY_STRING;+ payload: string;+}+export interface AddToSelectedField {+ type: typeof ADD_TO_SELECTED_FIELD;+ payload: IFieldMoveToSelected;+}++export interface UpdateLogs {+ type: typeof SET_LOGS;+ payload: ILog[];+}+export interface SetLogsLinesPerPage {+ type: typeof SET_LOG_LINES_PER_PAGE;+ payload: number;+}++export interface PreviousLogsLines {+ type: typeof GET_PREVIOUS_LOG_LINES;+}+export interface NextLogsLines {+ type: typeof GET_NEXT_LOG_LINES;+}+export interface ResetIdStartAndEnd {+ type: typeof RESET_ID_START_AND_END;+}+export interface SetLoading {+ type: typeof SET_LOADING;+ payload: boolean;+}+export interface SetLoadingAggregate {+ type: typeof SET_LOADING_AGGREGATE;+ payload: boolean;+}++export interface SetLogsAggregateSeries {+ type: typeof SET_LOGS_AGGREGATE_SERIES;+ payload: ILogsAggregate[];+}+export interface SetDetailedLogData {+ type: typeof SET_DETAILED_LOG_DATA;+ payload: ILog;+}++export interface ToggleLiveTail {+ type: typeof TOGGLE_LIVE_TAIL;+ payload: TLogsLiveTailState;+}+export interface PushLiveTailEvent {+ type: typeof PUSH_LIVE_TAIL_EVENT;+ payload: ILog[];+}+export interface StopLiveTail {+ type: typeof STOP_LIVE_TAIL;+}+export interface FlushLogs {+ type: typeof FLUSH_LOGS;+}+export interface SetLiveTailStartTime {+ type: typeof SET_LIVE_TAIL_START_TIME;+ payload: number;+}+// export interface GetServiceListLoading {+// type:+// | typeof GET_SERVICE_LIST_LOADING_START+// | typeof GET_INITIAL_APPLICATION_LOADING;+// }++// export interface GetServiceListError {+// type: typeof GET_SERVICE_LIST_ERROR | typeof GET_INITIAL_APPLICATION_ERROR;+// payload: {+// errorMessage: string;+// };+// }++// export interface GetInitialApplicationData {+// type: typeof GET_INTIAL_APPLICATION_DATA;+// payload: {+// topEndPoints: TopEndPoints[];+// // dbOverView: DBOverView[];+// // externalService: ExternalService[];+// // externalAverageDuration: ExternalAverageDuration[];+// // externalError: ExternalError[];+// serviceOverview: ServiceOverview[];+// };+// }++// export interface ResetInitialApplicationData {+// type: typeof RESET_INITIAL_APPLICATION_DATA;+// }++// export interface SetResourceAttributeQueries {+// type: typeof SET_RESOURCE_ATTRIBUTE_QUERIES;+// payload: {+// queries: IResourceAttributeQuery[];+// promQLQuery: string;+// };+// }++export type LogsActions =+ | GetFields+ | SetFields+ | SetSearchQueryString+ | SetSearchQueryParsedPayload+ | AddSearchFieldQueryString+ | AddToSelectedField+ | UpdateLogs+ | SetLogsLinesPerPage+ | PreviousLogsLines+ | NextLogsLines+ | ResetIdStartAndEnd+ | SetLoading+ | SetLoadingAggregate+ | SetLogsAggregateSeries+ | SetDetailedLogData+ | ToggleLiveTail+ | PushLiveTailEvent+ | StopLiveTail+ | FlushLogs+ | SetLiveTailStartTime;diff --git a/frontend/src/types/api/logs/addToSelectedFields.ts b/frontend/src/types/api/logs/addToSelectedFields.tsnew file mode 100644index 0000000000..0147f70c4a--- /dev/null+++ b/frontend/src/types/api/logs/addToSelectedFields.ts@@ -0,0 +1,4 @@+import { IFieldMoveToSelected } from './fields';++export type Props = IFieldMoveToSelected;+export type PayloadProps = IFieldMoveToSelected;diff --git a/frontend/src/types/api/logs/fields.ts b/frontend/src/types/api/logs/fields.tsnew file mode 100644index 0000000000..3c035a10c4--- /dev/null+++ b/frontend/src/types/api/logs/fields.ts@@ -0,0 +1,16 @@+export interface IField {+ name: string;+ type: string;+ dataType: string;+}++export interface IFields {+ selected: ISelectedFields[];+ interesting: IInterestingFields[];+}+export type ISelectedFields = IField;+export type IInterestingFields = IField;++export type IFieldMoveToSelected = IField & {+ selected: boolean;+};diff --git a/frontend/src/types/api/logs/getLogs.ts b/frontend/src/types/api/logs/getLogs.tsnew file mode 100644index 0000000000..6cf847b32d--- /dev/null+++ b/frontend/src/types/api/logs/getLogs.ts@@ -0,0 +1,9 @@+import { ILog } from './log';++export type PayloadProps = ILog[];+export type Props = {+ q: string;+ limit: number;+ orderBy: string;+ order: string;+};diff --git a/frontend/src/types/api/logs/getLogsAggregate.ts b/frontend/src/types/api/logs/getLogsAggregate.tsnew file mode 100644index 0000000000..2a92716f2c--- /dev/null+++ b/frontend/src/types/api/logs/getLogsAggregate.ts@@ -0,0 +1,12 @@+export type PayloadProps = Record<+ string,+ {+ timestamp: number;+ value: number;+ }+>;+export type Props = {+ timestampStart: number;+ timestampEnd: number;+ step: number;+};diff --git a/frontend/src/types/api/logs/getSearchFields.ts b/frontend/src/types/api/logs/getSearchFields.tsnew file mode 100644index 0000000000..8bf2524aea--- /dev/null+++ b/frontend/src/types/api/logs/getSearchFields.ts@@ -0,0 +1,3 @@+import { IFields } from './fields';++export type PayloadProps = IFields;diff --git a/frontend/src/types/api/logs/liveTail.ts b/frontend/src/types/api/logs/liveTail.tsnew file mode 100644index 0000000000..b2a7445ced--- /dev/null+++ b/frontend/src/types/api/logs/liveTail.ts@@ -0,0 +1 @@+export type TLogsLiveTailState = 'PLAYING' | 'PAUSED' | 'STOPPED';diff --git a/frontend/src/types/api/logs/log.ts b/frontend/src/types/api/logs/log.tsnew file mode 100644index 0000000000..ef61ba9871--- /dev/null+++ b/frontend/src/types/api/logs/log.ts@@ -0,0 +1,14 @@+export interface ILog {+ timestamp: number;+ id: string;+ traceId: string;+ spanId: string;+ traceFlags: number;+ severityText: string;+ severityNumber: number;+ body: string;+ resourcesString: Record<string, never>;+ attributesString: Record<string, never>;+ attributesInt: Record<string, never>;+ attributesFloat: Record<string, never>;+}diff --git a/frontend/src/types/api/logs/logAggregate.ts b/frontend/src/types/api/logs/logAggregate.tsnew file mode 100644index 0000000000..a397a0cced--- /dev/null+++ b/frontend/src/types/api/logs/logAggregate.ts@@ -0,0 +1,5 @@+export interface ILogsAggregate {+ timestamp: number;+ value: number;+ time: Date;+}diff --git a/frontend/src/types/api/logs/operator.ts b/frontend/src/types/api/logs/operator.tsnew file mode 100644index 0000000000..24043d9827--- /dev/null+++ b/frontend/src/types/api/logs/operator.ts@@ -0,0 +1,15 @@+export interface ILogSearchOperatorsCommon {+ Equal: 'EQ';+ 'Not Equal': 'NEQ';+ 'Greater Than': 'GT';+ 'Less Than': 'LT';+ 'Greater Than Equal': 'GTE';+ 'Less Than Equal': 'LTE';+ In: 'IN';+ 'Not In': 'NIN';+}++export interface ILogSearchOperatorsString extends ILogSearchOperatorsCommon {+ Like: 'LIKE';+ 'Not Like': 'NLIKE';+}diff --git a/frontend/src/types/api/logs/removeSelectedField.ts b/frontend/src/types/api/logs/removeSelectedField.tsnew file mode 100644index 0000000000..0147f70c4a--- /dev/null+++ b/frontend/src/types/api/logs/removeSelectedField.ts@@ -0,0 +1,4 @@+import { IFieldMoveToSelected } from './fields';++export type Props = IFieldMoveToSelected;+export type PayloadProps = IFieldMoveToSelected;diff --git a/frontend/src/types/api/settings/common.ts b/frontend/src/types/api/settings/common.tsindex 67c0c3ed03..3f1ad7dd78 100644--- a/frontend/src/types/api/settings/common.ts+++ b/frontend/src/types/api/settings/common.ts@@ -1 +1 @@-export type TTTLType = 'metrics' | 'traces';+export type TTTLType = 'metrics' | 'traces' | 'logs';diff --git a/frontend/src/types/api/settings/getRetention.ts b/frontend/src/types/api/settings/getRetention.tsindex 5f547ffd6c..da65763c08 100644--- a/frontend/src/types/api/settings/getRetention.ts+++ b/frontend/src/types/api/settings/getRetention.ts@@ -16,10 +16,20 @@ export interface PayloadPropsTraces {expected_traces_ttl_duration_hrs?: number;}+export interface PayloadPropsLogs {+ logs_ttl_duration_hrs: number;+ logs_move_ttl_duration_hrs?: number;+ status: TStatus;+ expected_logs_ttl_duration_hrs?: number;+ expected_logs_move_ttl_duration_hrs?: number;+}+export type Props = TTTLType;export type PayloadProps<T> = T extends 'metrics'? PayloadPropsMetrics: T extends 'traces'? PayloadPropsTraces+ : T extends 'logs'+ ? PayloadPropsLogs: never;diff --git a/frontend/src/types/reducer/logs.ts b/frontend/src/types/reducer/logs.tsnew file mode 100644index 0000000000..9a60ee5f3e--- /dev/null+++ b/frontend/src/types/reducer/logs.ts@@ -0,0 +1,26 @@+import { ILogQLParsedQueryItem } from 'lib/logql/types';+import { IFields } from 'types/api/logs/fields';+import { TLogsLiveTailState } from 'types/api/logs/liveTail';+import { ILog } from 'types/api/logs/log';+import { ILogsAggregate } from 'types/api/logs/logAggregate';++export interface ILogsReducer {+ fields: IFields;+ searchFilter: {+ queryString: string;+ parsedQuery: ILogQLParsedQueryItem[];+ };+ logs: ILog[];+ logLinesPerPage: number;+ idEnd: string;+ idStart: string;+ isLoading: boolean;+ isLoadingAggregate: boolean;+ logsAggregate: ILogsAggregate[];+ selectedLogId: string;+ detailedLog: null | ILog;+ liveTail: TLogsLiveTailState;+ liveTailStartRange: number; // time in minutes+}++export default ILogsReducer;diff --git a/frontend/src/utils/permission/index.ts b/frontend/src/utils/permission/index.tsindex 6f12d43225..56b9436a42 100644--- a/frontend/src/utils/permission/index.ts+++ b/frontend/src/utils/permission/index.ts@@ -68,4 +68,5 @@ export const routePermission: Record<keyof typeof ROUTES, ROLES[]> = {UN_AUTHORIZED: ['ADMIN', 'EDITOR', 'VIEWER'],USAGE_EXPLORER: ['ADMIN', 'EDITOR', 'VIEWER'],VERSION: ['ADMIN', 'EDITOR', 'VIEWER'],+ LOGS: ['ADMIN', 'EDITOR', 'VIEWER'],};diff --git a/frontend/yarn.lock b/frontend/yarn.lockindex f2d9ad04ad..7942a7c6d2 100644--- a/frontend/yarn.lock+++ b/frontend/yarn.lock@@ -1693,6 +1693,11 @@resolved "https://registry.yarnpkg.com/@mapbox/unitbezier/-/unitbezier-0.0.0.tgz#15651bd553a67b8581fb398810c98ad86a34524e"integrity sha512-HPnRdYO0WjFjRTSwO3frz1wKaU649OBFPX3Zo/2WZvuRi6zMiRGui8SnPQiQABgqCf8YikDe5t3HViTVw1WUzA==+"@microsoft/fetch-event-source@^2.0.1":+ version "2.0.1"+ resolved "https://registry.yarnpkg.com/@microsoft/fetch-event-source/-/fetch-event-source-2.0.1.tgz#9ceecc94b49fbaa15666e38ae8587f64acce007d"+ integrity sha512-W6CLUJ2eBMw3Rec70qrsEW0jOm/3twwJv21mrmj2yORiaVmVYGS4sSS5yUwvQc1ZlDLYGPnClVWmUUMagKNsfA==+"@monaco-editor/loader@^1.3.2":version "1.3.2"resolved "https://registry.yarnpkg.com/@monaco-editor/loader/-/loader-1.3.2.tgz#04effbb87052d19cd7d3c9d81c0635490f9bb6d8"@@ -6192,6 +6197,11 @@ etag@~1.8.1:resolved "https://registry.yarnpkg.com/etag/-/etag-1.8.1.tgz#41ae2eeb65efa62268aebfea83ac7d79299b0887"integrity sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=+event-source-polyfill@^1.0.28:+ version "1.0.28"+ resolved "https://registry.yarnpkg.com/event-source-polyfill/-/event-source-polyfill-1.0.28.tgz#9029143e6827c65b91b7edfb8528f8384930eff7"+ integrity sha512-S4Je04Br394hKTiyUXKAkNpha/7r172rLNu76sdxB3Nw2g9sjuEc4kxMu/miaikvWA4jvJ2x6Xkg6BOAb1aM7g==+[email protected], eventemitter3@^4.0.0:version "4.0.7"resolved "https://registry.yarnpkg.com/eventemitter3/-/eventemitter3-4.0.7.tgz#2de9b68f6528d5644ef5c59526a1b4a07306169f"@@ -6202,6 +6212,11 @@ events@^3.2.0:resolved "https://registry.yarnpkg.com/events/-/events-3.3.0.tgz#31a95ad0a924e2d2c419a813aeb2c4e878ea7400"integrity sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==+eventsource@^2.0.2:+ version "2.0.2"+ resolved "https://registry.yarnpkg.com/eventsource/-/eventsource-2.0.2.tgz#76dfcc02930fb2ff339520b6d290da573a9e8508"+ integrity sha512-IzUmBGPR3+oUG9dUeXynyNmf91/3zUSJg1lCktzKw47OXuhco54U3r9B7O4XX+Rb1Itm9OZ2b0RkTs10bICOxA==+exec-sh@^0.3.2:version "0.3.6"resolved "https://registry.yarnpkg.com/exec-sh/-/exec-sh-0.3.6.tgz#ff264f9e325519a60cb5e273692943483cca63bc"@@ -6538,6 +6553,11 @@ flat-cache@^3.0.4:flatted "^3.1.0"rimraf "^3.0.2"+flat@^5.0.2:+ version "5.0.2"+ resolved "https://registry.yarnpkg.com/flat/-/flat-5.0.2.tgz#8ca6fe332069ffa9d324c327198c598259ceb241"+ integrity sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==+flatted@^3.1.0:version "3.2.5"resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.5.tgz#76c8584f4fc843db64702a6bd04ab7a8bd666da3"