Skip to content

Commit e221344

Browse files
feat: custom logger (#13156)
* feat: custom logger * mock log * unit test * FF and jobs loader * unit test * add to ResourceLoader * get from container * mock * rm log * default logger mock * link loaders, express * comments * initialize container as first step * db conn * test * initialize start * plugin build using default logger * ignore .medusa * revert ignroe --------- Co-authored-by: Oli Juhl <[email protected]>
1 parent 9412669 commit e221344

File tree

42 files changed

+472
-211
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+472
-211
lines changed

.changeset/seven-pigs-build.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
"@medusajs/test-utils": patch
3+
"@medusajs/framework": patch
4+
"@medusajs/types": patch
5+
"@medusajs/utils": patch
6+
"@medusajs/medusa": patch
7+
---
8+
9+
feat: custom logger on medusa-config

packages/core/framework/src/config/config.ts

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { ConfigModule } from "./types"
21
import { deepCopy, isDefined } from "@medusajs/utils"
32
import { logger } from "../logger"
3+
import { ConfigModule } from "./types"
44

55
export class ConfigManager {
66
/**
@@ -124,21 +124,23 @@ export class ConfigManager {
124124

125125
/**
126126
* Normalizes the project config object and assign the defaults if needed
127-
* @param projectConfig
127+
* @param config
128128
* @protected
129129
*/
130130
protected normalizeProjectConfig(
131-
projectConfig: Partial<ConfigModule["projectConfig"]>
131+
config: Partial<ConfigModule>
132132
): ConfigModule["projectConfig"] {
133-
const outputConfig = deepCopy(
134-
projectConfig
135-
) as ConfigModule["projectConfig"]
133+
const projConfig = config?.projectConfig ?? {}
134+
const outputConfig = deepCopy(projConfig) as ConfigModule["projectConfig"]
136135

137136
if (!outputConfig?.redisUrl) {
138-
console.log(`redisUrl not found. A fake redis instance will be used.`)
137+
const customLogger = config?.logger ?? logger
138+
customLogger.log(
139+
`redisUrl not found. A fake redis instance will be used.`
140+
)
139141
}
140142

141-
outputConfig.http = this.buildHttpConfig(projectConfig)
143+
outputConfig.http = this.buildHttpConfig(projConfig)
142144

143145
let workerMode = outputConfig?.workerMode!
144146

@@ -172,9 +174,7 @@ export class ConfigManager {
172174
}): ConfigModule {
173175
this.#baseDir = baseDir
174176

175-
const normalizedProjectConfig = this.normalizeProjectConfig(
176-
projectConfig.projectConfig ?? {}
177-
)
177+
const normalizedProjectConfig = this.normalizeProjectConfig(projectConfig)
178178

179179
this.#config = {
180180
projectConfig: normalizedProjectConfig,
@@ -184,6 +184,7 @@ export class ConfigManager {
184184
modules: projectConfig.modules ?? {},
185185
featureFlags: projectConfig.featureFlags ?? {},
186186
plugins: projectConfig.plugins ?? [],
187+
logger: projectConfig.logger ?? logger,
187188
}
188189

189190
return this.#config

packages/core/framework/src/config/loader.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
import { ConfigModule } from "./types"
21
import { ContainerRegistrationKeys, getConfigFile } from "@medusajs/utils"
3-
import { logger } from "../logger"
4-
import { ConfigManager } from "./config"
5-
import { container } from "../container"
62
import { asFunction } from "awilix"
3+
import { container } from "../container"
4+
import { logger as defaultLogger } from "../logger"
5+
import { ConfigManager } from "./config"
6+
import { ConfigModule } from "./types"
77

88
const handleConfigError = (error: Error): void => {
9-
logger.error(`Error in loading config: ${error.message}`)
9+
defaultLogger.error(`Error in loading config: ${error.message}`)
1010
if (error.stack) {
11-
logger.error(error.stack)
11+
defaultLogger.error(error.stack)
1212
}
1313
process.exit(1)
1414
}
@@ -28,7 +28,7 @@ container.register(
2828
*/
2929
export async function configLoader(
3030
entryDirectory: string,
31-
configFileName: string
31+
configFileName: string = "medusa-config"
3232
): Promise<ConfigModule> {
3333
const config = await getConfigFile<ConfigModule>(
3434
entryDirectory,

packages/core/framework/src/feature-flags/feature-flag-loader.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import { asFunction } from "awilix"
1010
import { normalize } from "path"
1111
import { configManager } from "../config"
1212
import { container } from "../container"
13-
import { logger } from "../logger"
1413
import { FlagSettings } from "./types"
1514

1615
container.register(
@@ -25,7 +24,7 @@ container.register(
2524
export async function featureFlagsLoader(
2625
sourcePath?: string
2726
): Promise<FlagRouter> {
28-
const { featureFlags: projectConfigFlags = {} } = configManager.config
27+
const { featureFlags: projectConfigFlags = {}, logger } = configManager.config
2928

3029
if (!sourcePath) {
3130
return FeatureFlag

packages/core/framework/src/http/__fixtures__/server/index.ts

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,16 @@ import {
33
ModulesDefinition,
44
registerMedusaModule,
55
} from "@medusajs/modules-sdk"
6+
import { MedusaContainer } from "@medusajs/types"
67
import { ContainerRegistrationKeys, generateJwtToken } from "@medusajs/utils"
78
import { asValue } from "awilix"
89
import express from "express"
910
import querystring from "querystring"
1011
import supertest from "supertest"
11-
12-
import { MedusaContainer } from "@medusajs/types"
1312
import { configManager } from "../../../config"
1413
import { container } from "../../../container"
1514
import { featureFlagsLoader } from "../../../feature-flags"
16-
import { logger } from "../../../logger"
15+
import { logger as defaultLogger } from "../../../logger"
1716
import { ApiLoader } from "../../router"
1817
import { MedusaRequest } from "../../types"
1918
import { config } from "../mocks"
@@ -66,11 +65,8 @@ export const createServer = async (rootDir) => {
6665

6766
container.register(ContainerRegistrationKeys.PG_CONNECTION, asValue({}))
6867
container.register("configModule", asValue(config))
68+
container.register(ContainerRegistrationKeys.LOGGER, asValue(defaultLogger))
6969
container.register({
70-
logger: asValue({
71-
error: () => {},
72-
info: () => {},
73-
}),
7470
manager: asValue({}),
7571
})
7672

@@ -88,7 +84,7 @@ export const createServer = async (rootDir) => {
8884
})
8985

9086
await featureFlagsLoader()
91-
await moduleLoader({ container, moduleResolutions, logger })
87+
await moduleLoader({ container, moduleResolutions, logger: defaultLogger })
9288

9389
app.use((req, res, next) => {
9490
;(req as MedusaRequest).scope = container.createScope() as MedusaContainer
@@ -98,6 +94,7 @@ export const createServer = async (rootDir) => {
9894
await new ApiLoader({
9995
app,
10096
sourceDir: rootDir,
97+
container,
10198
}).load()
10299

103100
const superRequest = supertest(app)

packages/core/framework/src/http/__tests__/index.spec.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
1+
import {
2+
ContainerRegistrationKeys,
3+
createMedusaContainer,
4+
} from "@medusajs/utils"
5+
import { asValue } from "awilix"
16
import express from "express"
27
import { resolve } from "path"
8+
import { logger as defaultLogger } from "../../logger"
39
import {
410
customersCreateMiddlewareMock,
511
customersCreateMiddlewareValidatorMock,
612
customersGlobalMiddlewareMock,
713
storeGlobalMiddlewareMock,
814
} from "../__fixtures__/mocks"
915
import { createServer } from "../__fixtures__/server"
10-
import { MedusaNextFunction, ApiLoader } from "../index"
16+
import { ApiLoader, MedusaNextFunction } from "../index"
1117

1218
jest.setTimeout(30000)
1319

@@ -335,9 +341,16 @@ describe("RoutesLoader", function () {
335341
__dirname,
336342
"../__fixtures__/routers-duplicate-parameter"
337343
)
344+
const container = createMedusaContainer()
345+
container.register(
346+
ContainerRegistrationKeys.LOGGER,
347+
asValue(defaultLogger)
348+
)
349+
338350
const err = await new ApiLoader({
339351
app,
340352
sourceDir: rootDir,
353+
container,
341354
})
342355
.load()
343356
.catch((e) => e)

packages/core/framework/src/http/express-loader.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { MedusaContainer } from "@medusajs/framework/types"
2+
import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
13
import { dynamicImport } from "@medusajs/utils"
24
import createStore from "connect-redis"
35
import cookieParser from "cookie-parser"
@@ -7,14 +9,19 @@ import Redis from "ioredis"
79
import morgan from "morgan"
810
import path from "path"
911
import { configManager } from "../config"
10-
import { logger } from "../logger"
1112
import { MedusaRequest, MedusaResponse } from "./types"
1213

1314
const NOISY_ENDPOINTS_CHUNKS = ["@fs", "@id", "@vite", "@react", "node_modules"]
1415

1516
const isHealthCheck = (req: MedusaRequest) => req.path === "/health"
1617

17-
export async function expressLoader({ app }: { app: Express }): Promise<{
18+
export async function expressLoader({
19+
app,
20+
container,
21+
}: {
22+
app: Express
23+
container: MedusaContainer
24+
}): Promise<{
1825
app: Express
1926
shutdown: () => Promise<void>
2027
}> {
@@ -25,6 +32,7 @@ export async function expressLoader({ app }: { app: Express }): Promise<{
2532
const IS_DEV = NODE_ENV.startsWith("dev")
2633
const isStaging = NODE_ENV === "staging"
2734
const isTest = NODE_ENV === "test"
35+
const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
2836

2937
let sameSite: string | boolean = false
3038
let secure = false

packages/core/framework/src/http/router.ts

Lines changed: 33 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,31 @@
1-
import logger from "@medusajs/cli/dist/reporter"
1+
import { ContainerRegistrationKeys, parseCorsOrigins } from "@medusajs/utils"
22
import cors, { CorsOptions } from "cors"
3-
import { parseCorsOrigins } from "@medusajs/utils"
4-
import type { Express, RequestHandler, ErrorRequestHandler } from "express"
3+
import type { ErrorRequestHandler, Express, RequestHandler } from "express"
54
import type {
5+
AdditionalDataValidatorRoute,
6+
BodyParserConfigRoute,
7+
MedusaNextFunction,
68
MedusaRequest,
79
MedusaResponse,
10+
MiddlewareDescriptor,
11+
MiddlewareFunction,
812
MiddlewareVerb,
913
RouteDescriptor,
10-
MiddlewareFunction,
11-
MedusaNextFunction,
12-
MiddlewareDescriptor,
13-
BodyParserConfigRoute,
1414
RouteHandler,
15-
AdditionalDataValidatorRoute,
1615
} from "./types"
1716

18-
import { RoutesLoader } from "./routes-loader"
19-
import { RoutesFinder } from "./routes-finder"
20-
import { RoutesSorter } from "./routes-sorter"
21-
import { wrapHandler } from "./utils/wrap-handler"
22-
import { authenticate, AuthType } from "./middlewares"
23-
import { errorHandler } from "./middlewares/error-handler"
24-
import { RestrictedFields } from "./utils/restricted-fields"
17+
import { Logger, MedusaContainer } from "@medusajs/types"
18+
import { configManager } from "../config"
2519
import { MiddlewareFileLoader } from "./middleware-file-loader"
20+
import { authenticate, AuthType } from "./middlewares"
2621
import { createBodyParserMiddlewaresStack } from "./middlewares/bodyparser"
2722
import { ensurePublishableApiKeyMiddleware } from "./middlewares/ensure-publishable-api-key"
28-
import { configManager } from "../config"
23+
import { errorHandler } from "./middlewares/error-handler"
24+
import { RoutesFinder } from "./routes-finder"
25+
import { RoutesLoader } from "./routes-loader"
26+
import { RoutesSorter } from "./routes-sorter"
27+
import { RestrictedFields } from "./utils/restricted-fields"
28+
import { wrapHandler } from "./utils/wrap-handler"
2929

3030
export class ApiLoader {
3131
/**
@@ -58,18 +58,23 @@ export class ApiLoader {
5858
*/
5959
readonly #sourceDirs: string[]
6060

61+
readonly #logger: Logger
62+
6163
constructor({
6264
app,
6365
sourceDir,
6466
baseRestrictedFields = [],
67+
container,
6568
}: {
6669
app: Express
6770
sourceDir: string | string[]
6871
baseRestrictedFields?: string[]
72+
container: MedusaContainer
6973
}) {
7074
this.#app = app
7175
this.#sourceDirs = Array.isArray(sourceDir) ? sourceDir : [sourceDir]
7276
this.#assignRestrictedFields(baseRestrictedFields ?? [])
77+
this.#logger = container.resolve(ContainerRegistrationKeys.LOGGER)
7378
}
7479

7580
/**
@@ -105,7 +110,7 @@ export class ApiLoader {
105110
route: MiddlewareDescriptor | RouteDescriptor | RouteDescriptor
106111
) {
107112
if ("isRoute" in route) {
108-
logger.debug(`registering route ${route.method} ${route.matcher}`)
113+
this.#logger.debug(`registering route ${route.method} ${route.matcher}`)
109114
const handler = ApiLoader.traceRoute
110115
? ApiLoader.traceRoute(route.handler, {
111116
route: route.matcher,
@@ -118,7 +123,7 @@ export class ApiLoader {
118123
}
119124

120125
if (!route.methods) {
121-
logger.debug(`registering global middleware for ${route.matcher}`)
126+
this.#logger.debug(`registering global middleware for ${route.matcher}`)
122127
const handler = ApiLoader.traceMiddleware
123128
? (ApiLoader.traceMiddleware(route.handler, {
124129
route: route.matcher,
@@ -133,7 +138,9 @@ export class ApiLoader {
133138
? route.methods
134139
: [route.methods]
135140
methods.forEach((method) => {
136-
logger.debug(`registering route middleware ${method} ${route.matcher}`)
141+
this.#logger.debug(
142+
`registering route middleware ${method} ${route.matcher}`
143+
)
137144
const handler = ApiLoader.traceMiddleware
138145
? (ApiLoader.traceMiddleware(wrapHandler(route.handler), {
139146
route: route.matcher,
@@ -192,6 +199,7 @@ export class ApiLoader {
192199
| "shouldAppendStoreCors",
193200
corsOptions: CorsOptions
194201
) {
202+
const logger = this.#logger
195203
const corsFn = cors(corsOptions)
196204
const corsMiddleware: RequestHandler = function corsMiddleware(
197205
req,
@@ -234,6 +242,7 @@ export class ApiLoader {
234242
authType: AuthType | AuthType[],
235243
options?: { allowUnauthenticated?: boolean; allowUnregistered?: boolean }
236244
) {
245+
const logger = this.#logger
237246
logger.debug(`Registering auth middleware for prefix ${namespace}`)
238247

239248
const originalFn = authenticate(actorType, authType, options)
@@ -273,7 +282,9 @@ export class ApiLoader {
273282
namespace: string,
274283
routesFinder: RoutesFinder<BodyParserConfigRoute>
275284
): void {
276-
logger.debug(`Registering bodyparser middleware for prefix ${namespace}`)
285+
this.#logger.debug(
286+
`Registering bodyparser middleware for prefix ${namespace}`
287+
)
277288
this.#app.use(
278289
namespace,
279290
createBodyParserMiddlewaresStack(
@@ -292,6 +303,7 @@ export class ApiLoader {
292303
namespace: string,
293304
routesFinder: RoutesFinder<AdditionalDataValidatorRoute>
294305
) {
306+
const logger = this.#logger
295307
logger.debug(
296308
`Registering assignAdditionalDataValidator middleware for prefix ${namespace}`
297309
)
@@ -329,7 +341,7 @@ export class ApiLoader {
329341
* a `x-publishable-key` header
330342
*/
331343
#applyStorePublishableKeyMiddleware(namespace: string) {
332-
logger.debug(
344+
this.#logger.debug(
333345
`Registering publishable key middleware for namespace ${namespace}`
334346
)
335347
let middleware = ApiLoader.traceMiddleware

0 commit comments

Comments
 (0)