mirror of https://github.com/grafana/grafana
logs: json/logfmt-detection, simplify code (#61492)
* logs: json/logfmt: simplify code * remove obsolete comment Co-authored-by: Sven Grossmann <sven.grossmann@grafana.com> Co-authored-by: Sven Grossmann <sven.grossmann@grafana.com>pull/61497/head
parent
9b10f6c7dd
commit
ed88401a58
@ -0,0 +1,37 @@ |
|||||||
|
import { isLogLineJSON, isLogLineLogfmt } from './lineParser'; |
||||||
|
|
||||||
|
describe('isLogLineJSON', () => { |
||||||
|
test('should return false on empty line', () => { |
||||||
|
expect(isLogLineJSON('')).toBe(false); |
||||||
|
}); |
||||||
|
|
||||||
|
test('should return false on unknown line pattern', () => { |
||||||
|
expect(isLogLineJSON('To Be or not to be')).toBe(false); |
||||||
|
}); |
||||||
|
|
||||||
|
test('should return false on key value patterns', () => { |
||||||
|
expect(isLogLineJSON('foo=bar baz="41 + 1')).toBe(false); |
||||||
|
}); |
||||||
|
|
||||||
|
test('should return true on JSON log lines', () => { |
||||||
|
expect(isLogLineJSON('{"foo": "bar", "baz": "41 + 1"}')).toBe(true); |
||||||
|
}); |
||||||
|
}); |
||||||
|
|
||||||
|
describe('isLogLineLogfmt', () => { |
||||||
|
test('should return false on empty line', () => { |
||||||
|
expect(isLogLineLogfmt('')).toBe(false); |
||||||
|
}); |
||||||
|
|
||||||
|
test('should return false on unknown line pattern', () => { |
||||||
|
expect(isLogLineLogfmt('To Be or not to be')).toBe(false); |
||||||
|
}); |
||||||
|
|
||||||
|
test('should return true on key value patterns', () => { |
||||||
|
expect(isLogLineLogfmt('foo=bar baz="41 + 1')).toBe(true); |
||||||
|
}); |
||||||
|
|
||||||
|
test('should return false on JSON log lines', () => { |
||||||
|
expect(isLogLineLogfmt('{"foo": "bar", "baz": "41 + 1"}')).toBe(false); |
||||||
|
}); |
||||||
|
}); |
@ -0,0 +1,18 @@ |
|||||||
|
export function isLogLineJSON(line: string): boolean { |
||||||
|
let parsed; |
||||||
|
try { |
||||||
|
parsed = JSON.parse(line); |
||||||
|
} catch (error) {} |
||||||
|
// The JSON parser should only be used for log lines that are valid serialized JSON objects.
|
||||||
|
return typeof parsed === 'object'; |
||||||
|
} |
||||||
|
|
||||||
|
// This matches:
|
||||||
|
// first a label from start of the string or first white space, then any word chars until "="
|
||||||
|
// second either an empty quotes, or anything that starts with quote and ends with unescaped quote,
|
||||||
|
// or any non whitespace chars that do not start with quote
|
||||||
|
const LOGFMT_REGEXP = /(?:^|\s)([\w\(\)\[\]\{\}]+)=(""|(?:".*?[^\\]"|[^"\s]\S*))/; |
||||||
|
|
||||||
|
export function isLogLineLogfmt(line: string): boolean { |
||||||
|
return LOGFMT_REGEXP.test(line); |
||||||
|
} |
Loading…
Reference in new issue