-
Notifications
You must be signed in to change notification settings - Fork 312
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: createLoggerを少しリファクタリング (#2489)
- Loading branch information
Showing
1 changed file
with
25 additions
and
16 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,22 +1,31 @@ | ||
type LogLevel = "info" | "warn" | "error"; | ||
type LogFunction = (...args: unknown[]) => void; | ||
|
||
/** ログ出力用の関数を生成する。ブラウザ専用。 */ | ||
// TODO: window.backendをDIできるようにする | ||
export function createLogger(scope: string) { | ||
const createInner = | ||
( | ||
method: "logInfo" | "logWarn" | "logError", | ||
fallbackMethod: "info" | "warn" | "error", | ||
) => | ||
(...args: unknown[]) => { | ||
if (window.backend == undefined) { | ||
// eslint-disable-next-line no-console | ||
console[fallbackMethod](...args); | ||
export function createLogger(scope: string): Record<LogLevel, LogFunction> { | ||
return { | ||
info: createLogFunction("info"), | ||
warn: createLogFunction("warn"), | ||
error: createLogFunction("error"), | ||
}; | ||
|
||
function createLogFunction(logType: LogLevel): LogFunction { | ||
return (...args: unknown[]) => { | ||
if (window.backend != undefined) { | ||
const method = ( | ||
{ | ||
info: "logInfo", | ||
warn: "logWarn", | ||
error: "logError", | ||
} as const | ||
)[logType]; | ||
window.backend[method](`[${scope}]`, ...args); | ||
return; | ||
} | ||
window.backend[method](`[${scope}]`, ...args); | ||
|
||
// eslint-disable-next-line no-console | ||
console[logType](...args); | ||
}; | ||
return { | ||
info: createInner("logInfo", "info"), | ||
warn: createInner("logWarn", "warn"), | ||
error: createInner("logError", "error"), | ||
}; | ||
} | ||
} |