Skip to content

Instantly share code, notes, and snippets.

@josephdpurcell
Last active December 2, 2021 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephdpurcell/46227c241d102baeb77d91b594807369 to your computer and use it in GitHub Desktop.
Save josephdpurcell/46227c241d102baeb77d91b594807369 to your computer and use it in GitHub Desktop.
An opinionated Google Cloud structured logger
/**
* Google's logging enums:
* DEFAULT (0) The log entry has no assigned severity level.
* DEBUG (100) Debug or trace information.
* INFO (200) Routine information, such as ongoing status or performance.
* NOTICE (300) Normal but significant events, such as start up, shut down, or a configuration change.
* WARNING (400) Warning events might cause problems.
* ERROR (500) Error events are likely to cause problems.
* CRITICAL (600) Critical events cause more severe problems or outages.
* ALERT (700) A person must take an action immediately.
* EMERGENCY (800) One or more systems are unusable.
*/
export enum GoogleLogSeverity {
DEFAULT = 'DEFAULT',
DEBUG = 'DEBUG',
INFO = 'INFO',
NOTICE = 'NOTICE',
WARNING = 'WARNING',
ERROR = 'ERROR',
CRITICAL = 'CRITICAL',
ALERT = 'ALERT',
EMERGENCY = 'EMERGENCY'
}
/**
* A simple (opinionated) logger that can be used in a cloud function.
*
* If you're using it in an app, consider Pino logger.
*/
export class GcLogger {
default(message: string, context: any): void {
this.log(GoogleLogSeverity.DEFAULT, message, context);
}
debug(message: string, context: any): void {
this.log(GoogleLogSeverity.DEBUG, message, context);
}
info(message: string, context: any): void {
this.log(GoogleLogSeverity.INFO, message, context);
}
notice(message: string, context: any): void {
this.log(GoogleLogSeverity.NOTICE, message, context);
}
warning(message: string, context: any): void {
this.log(GoogleLogSeverity.WARNING, message, context);
}
error(message: string, context: any): void {
this.log(GoogleLogSeverity.ERROR, message, context);
}
critical(message: string, context: any): void {
this.log(GoogleLogSeverity.CRITICAL, message, context);
}
alert(message: string, context: any): void {
this.log(GoogleLogSeverity.ALERT, message, context);
}
emergency(message: string, context: any): void {
this.log(GoogleLogSeverity.EMERGENCY, message, context);
}
log(level: GoogleLogSeverity, message: string, context: any): void {
// Note: you could use process.stdout.write instead of console.log. The point here is just to get the log printed
// as a JSON object and Google will take care of the rest.
console.log(
JSON.stringify({
severity: level,
message: message,
context: context
})
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment