다음과 같은 콘솔 문자열이 있습니다.
2021-01-06T09:06:05.541212726Z D saveGarment: Function execution took 736 ms, finished with status code: 204
2021-01-06T09:06:10.844901031Z D saveGarment: Function execution started
2021-01-06T09:06:16.153Z ? saveGarment: CORE
2021-01-06T09:06:18.134508823Z D saveGarment: Function execution took 7470 ms, finished with status code: 200
2021-01-06T09:06:19.546Z ? saveGarment: { message: 'fail' }
이 문자열을 JSON으로 구문 분석하여 다음과 같이 표시하고 싶습니다.
{
{
date: '2021-01-06'
time: '09:06:05'
type: 'D'
function: 'saveGarment'
message: 'Function execution took 736 ms'
statusCode: 204
},
}
Regex를 사용하는 것이 약간 어려워 보입니다. 문자열 조작을 사용하여 처리합니다. 여기에 코드가 있습니다.
let consoleLog = `2021-01-06T09:06:05.541212726Z D saveGarment: Function execution took 736 ms, finished with status code: 204
2021-01-06T09:06:10.844901031Z D saveGarment: Function execution started
2021-01-06T09:06:16.153Z ? saveGarment: CORE
2021-01-06T09:06:18.134508823Z D saveGarment: Function execution took 7470 ms, finished with status code: 200
2021-01-06T09:06:19.546Z ? saveGarment: { message: 'fail' }`;
let logs = consoleLog.split('\n');
let results: any = [];
console.clear();
logs.forEach(log => {
let twoParts = splitFirstCh(log, ' ');
let dateTime = twoParts[0];
let twoParts1 = splitFirstCh(twoParts[1], ' ');
let typeStr = twoParts1[0];
let twoParts2 = splitFirstCh(twoParts1[1], ':');
let message = '', statusCode = '';
if (twoParts2[1].indexOf('status code') > -1) {
message = splitLastCh(twoParts2[1], ',')[0];
statusCode = splitLastCh(twoParts2[1], ':')[1].trim();
} else if (twoParts2[1].indexOf('{') > -1) {
message = splitLastCh(twoParts2[1], ':')[1].replace('}', '').trim();
statusCode = '';
} else {
message = twoParts2[1].trim();
statusCode = '';
}
let functionStr = twoParts2[0];
results.push({
date: new Date(dateTime).toLocaleDateString(),
time: new Date(dateTime).toLocaleTimeString(),
'type': typeStr,
'function': functionStr,
message: message,
statusCode: statusCode
});
});
console.log(results);
function splitFirstCh(data: string, ch: string) {
return [data.substr(0, data.indexOf(ch)), data.substr(data.indexOf(ch) + 1)];
}
function splitLastCh(data: string, ch: string) {
return [data.substr(0, data.lastIndexOf(ch)), data.substr(data.lastIndexOf(ch) + 1)];
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다