Skip to content

Commit aefab74

Browse files
committed
output morgan request and response
1 parent 1be9507 commit aefab74

File tree

4 files changed

+39
-1
lines changed

4 files changed

+39
-1
lines changed

backend/package-lock.json

Lines changed: 10 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

backend/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
"@elastic/elasticsearch": "^8.13.0",
2020
"@prisma/client": "^5.11.0",
2121
"@supabase/supabase-js": "^2.39.0",
22+
"@types/morgan": "^1.9.9",
2223
"csv-parse": "^5.5.6",
2324
"express": "^4.18.2",
2425
"morgan": "^1.10.0",

backend/src/app.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import express from "express"
22
import cors from "cors"
3+
import morgan from "morgan"
34
import swaggerUi from "swagger-ui-express"
45
import swaggerDocument from "../../openapi.json"
56
import UserController from "./controllers/UserController"
@@ -19,6 +20,33 @@ app.use(cors())
1920
app.use(express.json())
2021
app.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+
return `${method} ${url} ${status} ${prependStr}: ${JSON.stringify(body)}`
34+
})
35+
return bodyFormatName
36+
}
37+
38+
const appResponsePrototype = Object.getPrototypeOf(app.response)
39+
const originalSend = appResponsePrototype.send
40+
const morganBodyResponseSymbol = Symbol()
41+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
42+
appResponsePrototype.send = function sendOverWrite(body: any) {
43+
originalSend.call(this, body)
44+
this[morganBodyResponseSymbol] = body
45+
}
46+
47+
app.use(morgan(logBodyGen("Request", (req) => req.body)))
48+
app.use(morgan(logBodyGen("Response", (_req, res) => res[morganBodyResponseSymbol])))
49+
2250
app.get("/", (_req, res) => {
2351
res.status(200).send("Hello, world!")
2452
})

backend/src/controllers/SearchController.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,6 @@ class SearchController {
7878
})
7979

8080
const hits = result.hits.hits
81-
console.log(hits)
8281
if (hits.length === 0) {
8382
res.status(404).json({ error: "Not found" })
8483
return

0 commit comments

Comments
 (0)