@book000/node-utils 1.2.28 → 1.2.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,38 @@
1
+ import { Logger } from '@/logger'
2
+ import { Configuration, exampleConfiguration } from './example-configuration'
3
+ import { exampleLogger } from './example-logger'
4
+ import { exampleDiscord } from './example-discord'
5
+ import fs from 'node:fs'
6
+ import os from 'node:os'
7
+
8
+ async function main() {
9
+ const logger = Logger.configure('main')
10
+ logger.info('Running main()')
11
+
12
+ logger.info('Calling exampleLogger()')
13
+ exampleLogger()
14
+
15
+ logger.info('Create dummy configuration file')
16
+ const config: Configuration = {
17
+ foo: 'foo',
18
+ bar: 123,
19
+ }
20
+ const temporaryConfigPath = `${os.tmpdir()}/config.json`
21
+ fs.writeFileSync(temporaryConfigPath, JSON.stringify(config))
22
+
23
+ logger.info('Set environment variable')
24
+ process.env.CONFIG_PATH = temporaryConfigPath
25
+
26
+ logger.info('Calling exampleConfiguration()')
27
+ exampleConfiguration()
28
+
29
+ logger.info('Remove dummy configuration file')
30
+ fs.unlinkSync(temporaryConfigPath)
31
+
32
+ logger.info('Calling exampleDiscord()')
33
+ await exampleDiscord()
34
+ }
35
+
36
+ ;(async () => {
37
+ await main()
38
+ })()
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from './examples/example-configuration'
2
+ export * from './examples/example-discord'
3
+ export * from './examples/example-logger'
4
+ export * from './configuration'
5
+ export * from './discord'
6
+ export * from './logger'
package/src/logger.ts ADDED
@@ -0,0 +1,168 @@
1
+ import winston, { format } from 'winston'
2
+ import WinstonDailyRotateFile from 'winston-daily-rotate-file'
3
+ import { Format } from 'logform'
4
+ import cycle from 'cycle'
5
+
6
+ /**
7
+ * ロガーラッパークラス
8
+ */
9
+ export class Logger {
10
+ private readonly logger: winston.Logger
11
+
12
+ private constructor(logger: winston.Logger) {
13
+ this.logger = logger
14
+ }
15
+
16
+ /**
17
+ * デバッグログを出力する
18
+ *
19
+ * @param message メッセージ
20
+ * @param metadata メタデータ
21
+ */
22
+ public debug(message: string, metadata?: Record<string, unknown>): void {
23
+ this.logger.debug(message, metadata || {})
24
+ }
25
+
26
+ /**
27
+ * 情報ログを出力する
28
+ *
29
+ * @param message メッセージ
30
+ * @param metadata メタデータ
31
+ */
32
+ public info(message: string, metadata?: Record<string, unknown>): void {
33
+ this.logger.info(message, metadata || {})
34
+ }
35
+
36
+ /**
37
+ * 警告ログを出力する
38
+ *
39
+ * @param message メッセージ
40
+ * @param error エラー
41
+ */
42
+ public warn(message: string, error?: Error): void {
43
+ this.logger.warn(message, error)
44
+ }
45
+
46
+ /**
47
+ * エラーログを出力する
48
+ *
49
+ * @param message メッセージ
50
+ * @param error エラー
51
+ */
52
+ public error(message: string, error?: Error): void {
53
+ this.logger.error(message, error)
54
+ }
55
+
56
+ /**
57
+ * ロガーを初期化・設定する
58
+ *
59
+ * 環境変数で以下の設定が可能
60
+ * - LOG_LEVEL: ログレベル (デフォルト info)
61
+ * - LOG_FILE_LEVEL: ファイル出力のログレベル (デフォルト info)
62
+ * - LOG_DIR: ログ出力先 (デフォルト logs)
63
+ * - LOG_FILE_MAX_AGE: ログファイルの最大保存期間 (デフォルト 30d)
64
+ * - LOG_FILE_FORMAT: ログファイルのフォーマット (デフォルト text)
65
+ *
66
+ * @param category カテゴリ
67
+ * @returns ロガー
68
+ */
69
+ public static configure(category: string): Logger {
70
+ const logLevel = process.env.LOG_LEVEL || 'info'
71
+ const logFileLevel = process.env.LOG_FILE_LEVEL || 'info'
72
+ const logDirectory = process.env.LOG_DIR || 'logs'
73
+ const logFileMaxAge = process.env.LOG_FILE_MAX_AGE || '30d'
74
+ const selectLogFileFormat = process.env.LOG_FILE_FORMAT || 'text'
75
+
76
+ const textFormat = format.printf((info) => {
77
+ const { timestamp, level, message, ...rest } = info
78
+ // eslint-disable-next-line unicorn/no-array-reduce
79
+ const filteredRest = Object.keys(rest).reduce((accumulator, key) => {
80
+ if (key === 'stack') {
81
+ return accumulator
82
+ }
83
+ return {
84
+ ...accumulator,
85
+ [key]: rest[key],
86
+ }
87
+ }, {})
88
+ const standardLine = [
89
+ '[',
90
+ timestamp,
91
+ '] [',
92
+ category ?? '',
93
+ category ? '/' : '',
94
+ level.toLocaleUpperCase(),
95
+ ']: ',
96
+ message,
97
+ Object.keys(filteredRest).length > 0
98
+ ? ` (${JSON.stringify(filteredRest)})`
99
+ : '',
100
+ ].join('')
101
+ const errorLine = info.stack
102
+ ? info.stack.split('\n').slice(1).join('\n')
103
+ : undefined
104
+
105
+ return [standardLine, errorLine].filter((l) => l !== undefined).join('\n')
106
+ })
107
+ const logFileFormat =
108
+ selectLogFileFormat === 'ndjson' ? format.json() : textFormat
109
+ const decycleFormat = format((info) => cycle.decycle(info))
110
+ const fileFormat = format.combine(
111
+ ...([
112
+ format.errors({ stack: true }),
113
+ selectLogFileFormat === 'ndjson'
114
+ ? format.colorize({
115
+ message: true,
116
+ })
117
+ : format.uncolorize(),
118
+ decycleFormat(),
119
+ format.timestamp({
120
+ format: 'YYYY-MM-DD hh:mm:ss.SSS',
121
+ }),
122
+ logFileFormat,
123
+ ].filter((f) => f !== undefined) as Format[])
124
+ )
125
+ const consoleFormat = format.combine(
126
+ ...([
127
+ format.colorize({
128
+ message: true,
129
+ }),
130
+ decycleFormat(),
131
+ format.timestamp({
132
+ format: 'YYYY-MM-DD hh:mm:ss.SSS',
133
+ }),
134
+ textFormat,
135
+ ].filter((f) => f !== undefined) as Format[])
136
+ )
137
+ const extension = selectLogFileFormat === 'ndjson' ? 'ndjson' : 'log'
138
+ const transportRotateFile = new WinstonDailyRotateFile({
139
+ level: logFileLevel,
140
+ dirname: logDirectory,
141
+ filename: `%DATE%.` + extension,
142
+ datePattern: 'YYYY-MM-DD',
143
+ maxFiles: logFileMaxAge,
144
+ format: fileFormat,
145
+ auditFile: `${logDirectory}/audit.json`,
146
+ })
147
+
148
+ const logger = winston.createLogger({
149
+ transports: [
150
+ new winston.transports.Console({
151
+ level: logLevel,
152
+ format: consoleFormat,
153
+ }),
154
+ transportRotateFile,
155
+ ],
156
+ })
157
+ return new Logger(logger)
158
+ }
159
+ }
160
+
161
+ process.on('unhandledRejection', (reason) => {
162
+ const logger = Logger.configure('main')
163
+ logger.error('unhandledRejection', reason as Error)
164
+ })
165
+ process.on('uncaughtException', (error) => {
166
+ const logger = Logger.configure('main')
167
+ logger.error('uncaughtException', error)
168
+ })
package/tsconfig.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "ts-node": { "files": true },
3
+ "compilerOptions": {
4
+ "target": "es2020",
5
+ "module": "commonjs",
6
+ "moduleResolution": "Node",
7
+ "lib": ["ESNext", "esnext.AsyncIterable"],
8
+ "outDir": "./dist",
9
+ "removeComments": true,
10
+ "esModuleInterop": true,
11
+ "allowJs": true,
12
+ "checkJs": true,
13
+ "incremental": true,
14
+ "sourceMap": true,
15
+ "declaration": true,
16
+ "declarationMap": true,
17
+ "strict": true,
18
+ "noImplicitAny": true,
19
+ "strictBindCallApply": true,
20
+ "noUnusedLocals": true,
21
+ "noUnusedParameters": true,
22
+ "noImplicitReturns": true,
23
+ "noFallthroughCasesInSwitch": true,
24
+ "experimentalDecorators": true,
25
+ "baseUrl": ".",
26
+ "newLine": "LF",
27
+ "paths": {
28
+ "@/*": ["src/*"]
29
+ }
30
+ },
31
+ "include": ["src/**/*"]
32
+ }