Skip to content

Instantly share code, notes, and snippets.

@soyuka
Last active May 19, 2023 18:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save soyuka/8d3711c6cdc8c5b748f392ae24d5459c to your computer and use it in GitHub Desktop.
Save soyuka/8d3711c6cdc8c5b748f392ae24d5459c to your computer and use it in GitHub Desktop.
Nest / Angular shared Logger service https://github.com/nestjs/nest/issues/4487
import { Inject, Injectable, InjectionToken } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Logger, LogglyConfiguration, LOGGLY_CONFIG } from '@partenariat/logger';
@Injectable()
export class AngularLogglyLogger extends Logger {
constructor(http: HttpClient, @Inject(LOGGLY_CONFIG) configuration: LogglyConfiguration) {
super(http, configuration);
}
}
import { Observable } from 'rxjs';
export interface LogglyConfiguration {
token: string;
enabled: boolean;
tags: string[];
silent?: boolean;
}
export const LOGGLY_CONFIG = 'loggly.configuration';
export abstract class Logger {
private url: string;
constructor(
private http: Partial<{
post: (url: string, data: any) => Observable<any>;
}>,
private configuration: LogglyConfiguration
) {
this.url = `https://logs-01.loggly.com/inputs/${
configuration.token
}/tag/${configuration.tags.join(',')}/`;
}
error(error: Error) {
this.log(error.message, { stack: error.stack });
}
log(message: string, payload: any) {
if (!this.configuration.silent) {
console.error('Sending following log to loggly: ', message, payload);
}
if (!this.configuration.enabled) {
return;
}
this.http.post(this.url, { message, payload }).subscribe({
error: error => console.log('Error logging in loggly:', error)
});
}
}
import { HttpService, Injectable, Inject } from '@nestjs/common';
import { Logger, LogglyConfiguration, LOGGLY_CONFIG } from '@logger/logger';
@Injectable()
export class NestLogglyLogger extends Logger {
constructor(
http: HttpService,
@Inject(LOGGLY_CONFIG) configuration: LogglyConfiguration
) {
super(http, configuration);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment