Skip to content

Instantly share code, notes, and snippets.

@jarhoads
Last active February 7, 2020 19:18
Show Gist options
  • Save jarhoads/6348ca1578b32aad449ba4ad8a4a5d4d to your computer and use it in GitHub Desktop.
Save jarhoads/6348ca1578b32aad449ba4ad8a4a5d4d to your computer and use it in GitHub Desktop.
Models for a simple angular logging framework
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { timeout, map, catchError } from 'rxjs/operators';
export enum LogLevel {
Web = -1,
All = 0,
Debug = 1,
Info = 2,
Warn = 3,
Error = 4,
Fatal = 5,
Off = 6
}
export class LogEntry {
entryDate: Date = new Date();
level: LogLevel = LogLevel.Debug;
extraInfo: any[] = [];
logWithDate = true;
message = '';
buildLogString(): string {
let value = '';
if (this.logWithDate) { value = new Date() + ' - '; }
value += ('LogLevel: ' + LogLevel[this.level]);
value += (' - Message: ' + this.message);
if (this.extraInfo.length) {
value += (' - Additional Info: ' + this.formatParams(this.extraInfo));
}
return value;
}
private formatParams(params: any[]): string {
let ret: string = params.join(',');
if (params.some(p => typeof p === 'object')) {
ret = '';
for (const item of params) {
ret += (JSON.stringify(item) + ',');
}
}
return ret;
}
}
export interface ILoggable {
logLocation: string;
log(record: LogEntry): Observable<boolean>;
clear(): Observable<boolean>;
}
export class ConsoleLog implements ILoggable {
logLocation = 'console';
constructor() { }
log(entry: LogEntry): Observable<boolean> {
console.log(entry.buildLogString());
return of(true);
}
clear(): Observable<boolean> {
console.clear();
return of(true);
}
}
export class LocalStorageLog implements ILoggable {
logLocation = 'logDetails';
constructor() { }
log(entry: LogEntry): Observable<boolean> {
let ret = false;
let values: string[];
try {
values = this.getLocalValues();
values.push(entry.buildLogString());
localStorage.setItem(this.logLocation, JSON.stringify(values));
ret = true;
} catch (ex) {
console.log('Error logging to local storage: ' + ex);
}
return of(ret);
}
clear(): Observable<boolean> {
localStorage.setItem(this.logLocation, JSON.stringify([]));
return of(true);
}
empty(): boolean {
const values = this.getLocalValues();
if (values instanceof Array) {
return values.length <= 0;
} else {
return false;
}
}
getLocalValues() {
return JSON.parse(localStorage.getItem(this.logLocation)) || [];
}
getLogDetails(): string {
const values = this.getLocalValues();
// tslint:disable-next-line:quotemark
return 'log_details: ' + JSON.stringify(values).replace(/\\"/g, "'");
}
}
export class WebApiLog implements ILoggable {
logLocation = '/api/log';
constructor(private http: HttpClient) { }
log(entry: LogEntry): Observable<boolean> {
const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
const options = { headers };
const logTimeout = 5000;
const logEntry = entry.buildLogString();
// tslint:disable-next-line:quotemark
console.log(`Writing to http/webApi: location: ${this.logLocation} entry: ${JSON.stringify(logEntry).replace(/\\"/g, "'")}`);
return of(true);
// add implementation for wep api endpoint here
// return this.http.post(this.logLocation, entry, options)
// .pipe(
// timeout(logTimeout),
// map((response: any) => response),
// catchError(this.handleErrors)
// );
}
clear(): Observable<boolean> {
// returning true for now - can add api storage clearing here
return of(true);
}
private handleErrors(error: any): Observable<any> {
const errors: string[] = [];
let msg = '';
msg = 'Status: ' + error.status;
msg += ' - Status Text: ' + error.statusText;
if (error.json()) {
msg += ' - Exception Message: ' +
error.json().exceptionMessage;
}
errors.push(msg);
console.error('An error occurred', errors);
return Observable.throw(errors);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment