logixlysia 3.0.2 → 3.2.0

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## [3.2.0](https://github.com/PunGrumpy/logixlysia/compare/v3.1.0...v3.2.0) (2024-05-07)
4
+
5
+
6
+ ### Features
7
+
8
+ * update logger function name for clarity ([9badffc](https://github.com/PunGrumpy/logixlysia/commit/9badffc286fc13feda9eeffd28881990ae437c9f))
9
+
10
+ ## [3.1.0](https://github.com/PunGrumpy/logixlysia/compare/v3.0.2...v3.1.0) (2024-04-09)
11
+
12
+
13
+ ### Features
14
+
15
+ * **logger:** add log filtering functional ([af7d9ec](https://github.com/PunGrumpy/logixlysia/commit/af7d9ec5b2bb5ff5942d1a586be23a9d23a2c1cf)), closes [#38](https://github.com/PunGrumpy/logixlysia/issues/38)
16
+
17
+
18
+ ### Bug Fixes
19
+
20
+ * CI/CD GitHub Actions ([3c40092](https://github.com/PunGrumpy/logixlysia/commit/3c40092bd0ac7bf8bd601a299453cf5080224234))
21
+
3
22
  ## [3.0.2](https://github.com/PunGrumpy/logixlysia/compare/v3.0.1...v3.0.2) (2024-04-08)
4
23
 
5
24
 
package/README.md CHANGED
@@ -37,6 +37,7 @@ app.listen(3000)
37
37
  | ------------------ | --------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------- |
38
38
  | `ip` | `boolean` | Display the incoming IP address based on the `X-Forwarded-For` header | `false` |
39
39
  | `customLogMessage` | `string` | Custom log message to display | `🦊 {now} {level} {duration} {method} {pathname} {status} {message} {ip}` |
40
+ | `logFilter` | `object` | Filter the logs based on the level, method, and status | `null` |
40
41
 
41
42
  ## `📄` License
42
43
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "logixlysia",
3
- "version": "3.0.2",
3
+ "version": "3.2.0",
4
4
  "description": "🦊 Logixlysia is a logger for Elysia",
5
5
  "type": "module",
6
6
  "module": "src/index.ts",
package/src/index.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import Elysia from 'elysia'
2
- import { createLogger, handleHttpError } from './logger'
3
- import startString from './utils/start'
2
+ import startServer from './utils/start'
4
3
  import { Server } from 'bun'
5
4
  import { HttpError, Options } from './types'
5
+ import { createLogger } from './logger'
6
+ import { handleHttpError } from './logger/handle'
6
7
 
7
8
  /**
8
9
  * Creates a logger.
@@ -19,14 +20,14 @@ import { HttpError, Options } from './types'
19
20
  *
20
21
  * @returns {Elysia} The logger.
21
22
  */
22
- export const logger = (options?: Options): Elysia => {
23
+ export default function logixlysia(options?: Options): Elysia {
23
24
  const log = createLogger(options)
24
25
 
25
26
  const elysia = new Elysia({
26
27
  name: 'Logixlysia'
27
28
  })
28
29
  .onStart(ctx => {
29
- startString(ctx.server as Server)
30
+ startServer(ctx.server as Server)
30
31
  })
31
32
  .onRequest(ctx => {
32
33
  ctx.store = { beforeTime: process.hrtime.bigint() }
@@ -0,0 +1,52 @@
1
+ import { LogLevel, Options } from '~/types'
2
+
3
+ /**
4
+ * Filters log messages.
5
+ *
6
+ * @param {LogLevel} logLevel The log level.
7
+ * @param {number} status The status code.
8
+ * @param {string} method The method.
9
+ * @param {Options} options The options.
10
+ * @returns {boolean} `true` if the log message should be logged, otherwise `false`.
11
+ */
12
+ function filterLog(
13
+ logLevel: LogLevel,
14
+ status: number,
15
+ method: string,
16
+ options?: Options
17
+ ): boolean {
18
+ const filter = options?.config?.logFilter
19
+
20
+ if (!filter) return true
21
+
22
+ // Level
23
+ if (filter.level) {
24
+ if (Array.isArray(filter.level)) {
25
+ if (!filter.level.includes(logLevel)) return false
26
+ }
27
+ } else {
28
+ if (filter.level !== logLevel) return false
29
+ }
30
+
31
+ // Status
32
+ if (filter.status) {
33
+ if (Array.isArray(filter.status)) {
34
+ if (!filter.status.includes(status)) return false
35
+ }
36
+ } else {
37
+ if (filter.status !== status) return false
38
+ }
39
+
40
+ // Method
41
+ if (filter.method) {
42
+ if (Array.isArray(filter.method)) {
43
+ if (!filter.method.includes(method)) return false
44
+ }
45
+ } else {
46
+ if (filter.method !== method) return false
47
+ }
48
+
49
+ return true
50
+ }
51
+
52
+ export { filterLog }
@@ -0,0 +1,29 @@
1
+ import { HttpError, Options, RequestInfo, StoreData } from '~/types'
2
+ import { buildLogMessage } from '.'
3
+
4
+ /**
5
+ * Handles an HTTP error.
6
+ *
7
+ * @param {RequestInfo} request The request.
8
+ * @param {HttpError} error The HTTP error.
9
+ * @param {StoreData} store The store data.
10
+ * @param {Options} options The options.
11
+ */
12
+ function handleHttpError(
13
+ request: RequestInfo,
14
+ error: HttpError,
15
+ store: StoreData,
16
+ options?: Options
17
+ ): void {
18
+ const statusCode = error.status || 500
19
+ const logMessage = buildLogMessage(
20
+ 'ERROR',
21
+ request,
22
+ { status: statusCode },
23
+ store,
24
+ options
25
+ )
26
+ console.error(logMessage)
27
+ }
28
+
29
+ export { handleHttpError }
@@ -1,18 +1,18 @@
1
- import chalk from 'chalk'
2
- import durationString from './utils/duration'
3
- import methodString from './utils/method'
4
- import logString from './utils/log'
5
- import pathString from './utils/path'
6
- import statusString from './utils/status'
7
1
  import {
8
- LogLevel,
9
2
  LogData,
10
3
  Logger,
11
- StoreData,
4
+ LogLevel,
12
5
  Options,
13
6
  RequestInfo,
14
- HttpError
15
- } from './types'
7
+ StoreData
8
+ } from '~/types'
9
+ import { filterLog } from './filter'
10
+ import chalk from 'chalk'
11
+ import logString from '~/utils/log'
12
+ import durationString from '~/utils/duration'
13
+ import methodString from '~/utils/method'
14
+ import pathString from '~/utils/path'
15
+ import statusString from '~/utils/status'
16
16
 
17
17
  /**
18
18
  * Logs a message.
@@ -30,6 +30,10 @@ function log(
30
30
  store: StoreData,
31
31
  options?: Options
32
32
  ): void {
33
+ if (!filterLog(level, data.status || 200, request.method, options)) {
34
+ return
35
+ }
36
+
33
37
  const logMessage = buildLogMessage(level, request, data, store, options)
34
38
  console.log(logMessage)
35
39
  }
@@ -85,33 +89,12 @@ function buildLogMessage(
85
89
  * @param {Options} options The options.
86
90
  * @returns {Logger} The logger.
87
91
  */
88
- export const createLogger = (options?: Options): Logger => ({
89
- log: (level, request, data, store) =>
90
- log(level, request, data, store, options),
91
- customLogFormat: options?.config?.customLogFormat
92
- })
93
-
94
- /**
95
- * Handles an HTTP error.
96
- *
97
- * @param {RequestInfo} request The request.
98
- * @param {HttpError} error The HTTP error.
99
- * @param {StoreData} store The store data.
100
- * @param {Options} options The options.
101
- */
102
- export const handleHttpError = (
103
- request: RequestInfo,
104
- error: HttpError,
105
- store: StoreData,
106
- options?: Options
107
- ): void => {
108
- const statusCode = error.status || 500
109
- const logMessage = buildLogMessage(
110
- 'ERROR',
111
- request,
112
- { status: statusCode },
113
- store,
114
- options
115
- )
116
- console.error(logMessage)
92
+ function createLogger(options?: Options): Logger {
93
+ return {
94
+ log: (level, request, data, store) =>
95
+ log(level, request, data, store, options),
96
+ customLogFormat: options?.config?.customLogFormat
97
+ }
117
98
  }
99
+
100
+ export { log, buildLogMessage, createLogger }
package/src/types.ts CHANGED
@@ -48,6 +48,11 @@ interface Options {
48
48
  config?: {
49
49
  ip?: boolean
50
50
  customLogFormat?: string
51
+ logFilter?: {
52
+ level?: LogLevel | LogLevel[]
53
+ method?: string | string[]
54
+ status?: number | number[]
55
+ } | null
51
56
  }
52
57
  }
53
58
 
@@ -21,7 +21,7 @@ function createBoxText(text: string, width: number): string {
21
21
  *
22
22
  * @returns {void} The server string.
23
23
  */
24
- function startString(config: Server): void {
24
+ function startServer(config: Server): void {
25
25
  const { hostname, port, protocol } = config
26
26
  const ELYSIA_VERSION = import.meta.require('elysia/package.json').version
27
27
  const title = `Elysia v${ELYSIA_VERSION}`
@@ -41,4 +41,4 @@ function startString(config: Server): void {
41
41
  `)
42
42
  }
43
43
 
44
- export default startString
44
+ export default startServer
@@ -1,7 +1,7 @@
1
1
  import { Elysia } from 'elysia'
2
2
  import { edenTreaty } from '@elysiajs/eden'
3
3
  import { describe, it, expect, beforeAll, beforeEach } from 'bun:test'
4
- import { logger } from '../src'
4
+ import logixlysia from '../src'
5
5
 
6
6
  describe('Logixlysia with IP logging enabled', () => {
7
7
  let server: Elysia
@@ -11,7 +11,7 @@ describe('Logixlysia with IP logging enabled', () => {
11
11
  beforeAll(() => {
12
12
  server = new Elysia()
13
13
  .use(
14
- logger({
14
+ logixlysia({
15
15
  config: {
16
16
  ip: true,
17
17
  customLogFormat:
@@ -70,7 +70,7 @@ describe('Logixlysia with IP logging disabled', () => {
70
70
  beforeAll(() => {
71
71
  server = new Elysia()
72
72
  .use(
73
- logger({
73
+ logixlysia({
74
74
  config: {
75
75
  ip: false,
76
76
  customLogFormat:
@@ -124,3 +124,106 @@ describe('Logixlysia with IP logging disabled', () => {
124
124
  expect(error).toBeInstanceOf(Error)
125
125
  })
126
126
  })
127
+
128
+ describe('Logixlysia with log filtering enabled', () => {
129
+ let server: Elysia
130
+ let app: any
131
+ let logs: string[] = []
132
+
133
+ beforeAll(() => {
134
+ server = new Elysia()
135
+ .use(
136
+ logixlysia({
137
+ config: {
138
+ logFilter: {
139
+ level: 'INFO',
140
+ status: [200, 404],
141
+ method: 'GET'
142
+ }
143
+ }
144
+ })
145
+ )
146
+ .get('/', () => '🦊 Logixlysia Getting')
147
+ .post('logixlysia', () => '🦊 Logixlysia Posting')
148
+ .listen(3000)
149
+
150
+ app = edenTreaty<typeof server>('http://127.0.0.1:3000')
151
+ })
152
+
153
+ beforeEach(() => {
154
+ logs = []
155
+ })
156
+
157
+ it("Logs 'GET' requests with status 200 or 404 when log filtering criteria are met", async () => {
158
+ const requestCount = 5
159
+
160
+ for (let i = 0; i < requestCount; i++) {
161
+ logs.push((await app.get('/')).data)
162
+ }
163
+
164
+ expect(logs.length).toBe(requestCount)
165
+ logs.forEach(log => {
166
+ expect(log).toMatch('🦊 Logixlysia Getting')
167
+ })
168
+ })
169
+
170
+ it("Doesn't log 'POST' requests when log filtering criteria are not met", async () => {
171
+ const requestCount = 5
172
+
173
+ for (let i = 0; i < requestCount; i++) {
174
+ await app.post('/logixlysia', {})
175
+ }
176
+
177
+ expect(logs.length).toBe(0)
178
+ })
179
+
180
+ const otherMethods = ['PUT', 'DELETE', 'PATCH', 'HEAD'] // OPTIONS is failed (IDK why)
181
+ otherMethods.forEach(async method => {
182
+ it(`Logs '${method}' requests with status 200 or 404 when log filtering criteria are met`, async () => {
183
+ const requestCount = 5
184
+
185
+ for (let i = 0; i < requestCount; i++) {
186
+ logs.push((await app[method.toLowerCase()]('/')).data)
187
+ }
188
+
189
+ expect(logs.length).toBe(requestCount)
190
+ })
191
+ })
192
+ })
193
+
194
+ describe('Logixlysia with log filtering disabled', () => {
195
+ let server: Elysia
196
+ let app: any
197
+ let logs: string[] = []
198
+
199
+ beforeAll(() => {
200
+ server = new Elysia()
201
+ .use(
202
+ logixlysia({
203
+ config: {
204
+ logFilter: null
205
+ }
206
+ })
207
+ )
208
+ .get('/', () => '🦊 Logixlysia Getting')
209
+ .post('logixlysia', () => '🦊 Logixlysia Posting')
210
+ .listen(3000)
211
+
212
+ app = edenTreaty<typeof server>('http://127.0.0.1:3000')
213
+ })
214
+
215
+ beforeEach(() => {
216
+ logs = []
217
+ })
218
+
219
+ it('Logs all requests when log filtering is disabled', async () => {
220
+ const requestCount = 5
221
+
222
+ for (let i = 0; i < requestCount; i++) {
223
+ logs.push((await app.get('/')).data)
224
+ logs.push((await app.post('/logixlysia', {})).data)
225
+ }
226
+
227
+ expect(logs.length).toBe(requestCount * 2)
228
+ })
229
+ })
@@ -1,6 +1,6 @@
1
1
  import { afterEach, beforeEach, describe, expect, it, jest } from 'bun:test'
2
2
  import { Server } from '~/types'
3
- import startString from '~/utils/start'
3
+ import startServer from '~/utils/start'
4
4
 
5
5
  describe('Start String', () => {
6
6
  let originalConsoleLog: any
@@ -23,7 +23,7 @@ describe('Start String', () => {
23
23
  protocol: 'http'
24
24
  }
25
25
 
26
- startString(config)
26
+ startServer(config)
27
27
 
28
28
  const expectedMessage = `🦊 Elysia is running at http://localhost:3000`
29
29