Merge pull request #25456 from Zaperex/update-router-log-middleware

chore: remove personal identifiable information (PII) from logs
This commit is contained in:
Ben Lambert
2024-08-14 09:50:37 +02:00
committed by GitHub
4 changed files with 40 additions and 3 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@backstage/backend-defaults': patch
---
update the `morgan` middleware to use a custom format to prevent PII from being logged
@@ -243,6 +243,7 @@ Mkdocs
monorepo
Monorepo
monorepos
morgan
msgraph
msw
multiton
@@ -52,19 +52,49 @@ You can configure the root HTTP Router service by passing the options to the `cr
```ts
import { rootHttpRouterServiceFactory } from '@backstage/backend-app-api';
import { RequestHandler } from 'express';
import morgan from 'morgan';
const backend = createBackend();
backend.add(
rootHttpRouterServiceFactory({
configure: ({ app, middleware, routes, config, logger, lifecycle }) => {
// Refer to https://expressjs.com/en/guide/writing-middleware.html on how to write express middleware
const customMiddleware = {
logging(): RequestHandler {
const middlewareLogger = logger.child({
type: 'incomingRequest',
});
return (req, res, next) => {
// Custom Logging Implementation
next();
};
},
// Default logging middleware uses the [morgan](https://github.com/expressjs/morgan) middleware which you can configure with custom formats.
morganLogging(): RequestHandler {
const middlewareLogger = logger.child({
type: 'incomingRequest',
});
const customMorganFormat =
'[:date[clf]] ":method :url HTTP/:http-version" :status ":user-agent"';
return morgan(customMorganFormat, {
stream: {
write(message: string) {
logger.info(message.trimEnd());
},
},
});
},
};
// the built in middleware is provided through an option in the configure function
app.use(middleware.helmet());
app.use(middleware.cors());
app.use(middleware.compression());
// you can add you your own middleware in here
app.use(custom.logging());
app.use(customMiddleware.logging());
// here the routes that are registered by other plugins
app.use(routes);
@@ -140,8 +140,9 @@ export class MiddlewareFactory {
const logger = this.#logger.child({
type: 'incomingRequest',
});
return morgan('combined', {
const customMorganFormat =
'[:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"';
return morgan(customMorganFormat, {
stream: {
write(message: string) {
logger.info(message.trimEnd());