Logs: Fix creating of detected fields for each letter in log line (#40507)

* Logs: Fix using of JSON parser for strings

* Update packages/grafana-data/src/utils/logs.ts

* Update packages/grafana-data/src/utils/logs.ts

* Update parser typing and documentation
This commit is contained in:
Ivana Huckova 2021-10-18 11:16:24 +02:00 committed by GitHub
parent 2de769420e
commit 4e1cf7dea7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 8 additions and 3 deletions

View File

@ -132,9 +132,9 @@ export interface LogsParser {
getValueFromField: (field: string) => string; getValueFromField: (field: string) => string;
/** /**
* Function to verify if this is a valid parser for the given line. * Function to verify if this is a valid parser for the given line.
* The parser accepts the line unless it returns undefined. * The parser accepts the line if it returns true.
*/ */
test: (line: string) => any; test: (line: string) => boolean;
} }
export enum LogsDedupDescription { export enum LogsDedupDescription {

View File

@ -165,6 +165,7 @@ describe('LogsParsers', () => {
test('should detect format', () => { test('should detect format', () => {
expect(parser.test('foo')).toBeFalsy(); expect(parser.test('foo')).toBeFalsy();
expect(parser.test('"foo"')).toBeFalsy();
expect(parser.test('{"foo":"bar"}')).toBeTruthy(); expect(parser.test('{"foo":"bar"}')).toBeTruthy();
}); });

View File

@ -83,9 +83,13 @@ export const LogsParsers: { [name: string]: LogsParser } = {
getLabelFromField: (field) => (field.match(/^"([^"]+)"\s*:/) || [])[1], getLabelFromField: (field) => (field.match(/^"([^"]+)"\s*:/) || [])[1],
getValueFromField: (field) => (field.match(/:\s*(.*)$/) || [])[1], getValueFromField: (field) => (field.match(/:\s*(.*)$/) || [])[1],
test: (line) => { test: (line) => {
let parsed;
try { try {
return JSON.parse(line); parsed = JSON.parse(line);
} catch (error) {} } catch (error) {}
// The JSON parser should only be used for log lines that are valid serialized JSON objects.
// If it would be used for a string, detected fields would include each letter as a separate field.
return typeof parsed === 'object';
}, },
}, },