Synchronous logger lib (Winston) can't use headers() function anymore now it's async #74491
-
Hi, I use the Winston logging library for my Next.js app. However, now that the headers() method is asynchronous, I can't do that anymore. Indeed, Winston formatters can't be asynchronous. I know I could use Any idea how I could work around this? See below the code I currently use with the import { headers, type UnsafeUnwrappedHeaders } from "next/headers";
import { createLogger, format, transports } from "winston";
const { colorize, combine, printf } = format;
const myFormat = printf((info) => {
let requestId;
try {
const currentHeaders = headers() as unknown as UnsafeUnwrappedHeaders;
requestId = currentHeaders.get("x-request-id");
} catch (e) {
// not in a request context
}
const logParts: string[] = [];
logParts.push(`[${info.level}]`);
if (requestId) {
logParts.push(`[${requestId}]`);
}
logParts.push(info.message);
(...)
return logParts.join(" ");
});
const logger = createLogger({
level: "debug",
format: combine(fixErrors(), colorize(), myFormat),
transports: [new transports.Console()],
});
export default logger; |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I may have found a solution by wrapping the logger: export default {
debug(message: string, ...meta: any[]) {
logWithHeaders("debug", message, ...meta);
},
info(message: string, ...meta: any[]) {
logWithHeaders("info", message, ...meta);
},
warn(message: string, ...meta: any[]) {
logWithHeaders("warn", message, ...meta);
},
error(message: string, ...meta: any[]) {
logWithHeaders("error", message, ...meta);
},
};
function logWithHeaders(level: string, message: string, ...meta: any[]) {
let headersPromise: Promise<Headers | undefined>;
try {
headersPromise = headers().catch(() => undefined);
} catch (e) {
headersPromise = Promise.resolve(undefined);
}
headersPromise.then((headerList) =>
logger.child({ headerList }).log(level, message, ...meta),
);
} Now I have access to the headers in the |
Beta Was this translation helpful? Give feedback.
I may have found a solution by wrapping the logger: