1// Copyright 2023 The Pigweed Authors 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); you may not 4// use this file except in compliance with the License. You may obtain a copy of 5// the License at 6// 7// https://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12// License for the specific language governing permissions and limitations under 13// the License. 14 15import { Field, LogEntry } from './shared/interfaces'; 16import { downloadTextLogs } from './utils/download'; 17 18export class LogStore { 19 private logs: LogEntry[] = []; 20 private columnOrder: string[] = []; 21 22 addLogEntry(logEntry: LogEntry) { 23 this.logs.push(logEntry); 24 } 25 26 downloadLogs() { 27 const logs = this.getLogs(); 28 const headers = this.getHeaders(logs[0]?.fields); 29 const fileName = 'logs'; 30 downloadTextLogs(logs, headers, fileName); 31 } 32 33 getLogs(): LogEntry[] { 34 return this.logs; 35 } 36 37 setColumnOrder(colOrder: string[]) { 38 this.columnOrder = [...new Set(colOrder)]; 39 } 40 41 /** 42 * Helper to order header columns on download 43 * @param headerCol Header column from logs 44 * @return Ordered header columns 45 */ 46 private getHeaders(headerCol: Field[]): string[] { 47 if (!headerCol) { 48 return []; 49 } 50 51 const order = this.columnOrder; 52 if (order.indexOf('level') != 0) { 53 const index = order.indexOf('level'); 54 if (index != -1) { 55 order.splice(index, 1); 56 } 57 order.unshift('level'); 58 } 59 60 if (order.indexOf('message') != order.length) { 61 const index = order.indexOf('message'); 62 if (index != -1) { 63 order.splice(index, 1); 64 } 65 order.push('message'); 66 } 67 68 headerCol.forEach((field) => { 69 if (!order.includes(field.key)) { 70 order.splice(order.length - 1, 0, field.key); 71 } 72 }); 73 74 return order; 75 } 76} 77