Created
July 1, 2025 01:02
-
-
Save tanishqkancharla/168b4ffe3675734fee8088fd37dd79bb to your computer and use it in GitHub Desktop.
ORPC Logging Plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Context, ORPCError } from "@orpc/server"; | |
import type { | |
StandardHandlerOptions, | |
StandardHandlerPlugin, | |
} from "@orpc/server/standard"; | |
function formatNow() { | |
return new Date().toLocaleDateString("en-US", { | |
month: "short", | |
day: "numeric", | |
year: "numeric", | |
hour: "numeric", | |
minute: "2-digit", | |
hour12: true, | |
}); | |
} | |
export class LoggingPlugin<T extends Context> | |
implements StandardHandlerPlugin<T> | |
{ | |
init(options: StandardHandlerOptions<T>): void { | |
options.rootInterceptors ??= []; | |
options.rootInterceptors.push(async (interceptorOptions) => { | |
const start = Date.now(); | |
const { request } = interceptorOptions; | |
const { method, url } = request; | |
const path = url.pathname; | |
try { | |
const result = await interceptorOptions.next(); | |
const status = result.response?.status; | |
const duration = Date.now() - start; | |
console.log( | |
`${formatNow()} | ${method} ${path} | ${status} | ${duration}ms`, | |
); | |
return result; | |
} catch (error) { | |
const duration = Date.now() - start; | |
const status = | |
error instanceof ORPCError | |
? error.code === "UNAUTHORIZED" | |
? 401 | |
: error.code === "BAD_REQUEST" | |
? 400 | |
: error.code === "NOT_FOUND" | |
? 404 | |
: 500 | |
: 500; | |
console.error(error); | |
console.log( | |
`${formatNow()} | ${method} ${path} | ${status} | ${duration}ms`, | |
); | |
throw error; | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment