Skip to content

Instantly share code, notes, and snippets.

@aldy505
Last active April 2, 2025 01:36
Show Gist options
  • Save aldy505/2d0b6ac49a888924b2252ef356e7ff53 to your computer and use it in GitHub Desktop.
Save aldy505/2d0b6ac49a888924b2252ef356e7ff53 to your computer and use it in GitHub Desktop.
Sentry fanout logger -- early version
import type { Logger as PinoLogger } from "pino";
export interface Logger {
trace(message: string, attributes?: Record<string, unknown>): void;
debug(message: string, attributes?: Record<string, unknown>): void;
info(message: string, attributes?: Record<string, unknown>): void;
warn(message: string, attributes?: Record<string, unknown>): void;
error(message: string, attributes?: Record<string, unknown>): void;
fatal(message: string, attributes?: Record<string, unknown>): void;
}
export function pinoWrapper(pino: PinoLogger): Logger {
return {
trace: (message, attributes) => {
if (attributes == null) {
pino.trace(message);
return;
}
pino.trace(attributes, message);
},
debug: (message, attributes) => {
if (attributes == null) {
pino.debug(message);
return;
}
pino.debug(attributes, message);
},
info: (message, attributes) => {
if (attributes == null) {
pino.info(message);
return;
}
pino.info(attributes, message);
},
warn: (message, attributes) => {
if (attributes == null) {
pino.warn(message);
return;
}
pino.warn(attributes, message);
},
error: (message, attributes) => {
if (attributes == null) {
pino.error(message);
return;
}
},
fatal: (message, attributes) => {
if (attributes == null) {
pino.fatal(message);
return;
}
pino.fatal(attributes, message);
},
};
}
export function fanoutLogger(...loggers: Logger[]): Logger {
return {
trace: (message, attributes) => {
for (const logger of loggers) {
logger.trace(message, attributes);
}
},
debug: (message, attributes) => {
for (const logger of loggers) {
logger.debug(message, attributes);
}
},
info: (message, attributes) => {
for (const logger of loggers) {
logger.info(message, attributes);
}
},
warn: (message, attributes) => {
for (const logger of loggers) {
logger.warn(message, attributes);
}
},
error: (message, attributes) => {
for (const logger of loggers) {
logger.error(message, attributes);
}
},
fatal: (message, attributes) => {
for (const logger of loggers) {
logger.fatal(message, attributes);
}
},
};
}
// Usage!
import { pino } from "pino";
import * as Sentry from "@sentry/node";
const logger: Logger = fanoutLogger(Sentry.logger, pinoWrapper(pino()));
const error = new Error("something is wrong!");
logger.error("Something definitely went wrong!", {
err: error,
component: "billing-service",
user_id: "johndoe",
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment