11import express from "express"
22import cors from "cors"
3+ import morgan from "morgan"
34import swaggerUi from "swagger-ui-express"
45import swaggerDocument from "../../openapi.json"
56import UserController from "./controllers/UserController"
@@ -19,6 +20,35 @@ app.use(cors())
1920app . use ( express . json ( ) )
2021app . use ( express . urlencoded ( { extended : true } ) )
2122
23+ // morgan でリクエストボディとレスポンスボディをログ出力する
24+ // Ref: https://www.npmjs.com/package/morgan-body
25+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
26+ function logBodyGen ( prependStr : string , getBodyFunc : ( req : any , res : any ) => string ) {
27+ const bodyFormatName = "bodyFmt_" + prependStr
28+ morgan . format ( bodyFormatName , function logBody ( _ , req , res ) {
29+ const url = req . url
30+ const method = req . method
31+ const status = res . statusCode
32+ const body = getBodyFunc ( req , res )
33+ const timeStamp = new Date ( ) . toISOString ( )
34+ return `[${ timeStamp } ] ${ method } ${ url } ${ status } ${ prependStr } : ${ JSON . stringify ( body ) } `
35+ } )
36+ return bodyFormatName
37+ }
38+
39+ const appResponsePrototype = Object . getPrototypeOf ( app . response )
40+ const originalSend = appResponsePrototype . send
41+ const morganBodyResponseSymbol = Symbol ( )
42+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
43+ appResponsePrototype . send = function sendOverWrite ( body : any ) {
44+ originalSend . call ( this , body )
45+ this [ morganBodyResponseSymbol ] = body
46+ }
47+
48+ app . use ( morgan ( "[:date[iso]] :method :url :status ResponseTime :response-time ms" ) )
49+ app . use ( morgan ( logBodyGen ( "RequestBody" , ( req ) => req . body ) ) )
50+ app . use ( morgan ( logBodyGen ( "ResponseBody" , ( _req , res ) => res [ morganBodyResponseSymbol ] ) ) )
51+
2252app . get ( "/" , ( _req , res ) => {
2353 res . status ( 200 ) . send ( "Hello, world!" )
2454} )
0 commit comments