This repository was archived by the owner on Apr 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
[L2B-4977] Refactor logger to allow for custom backends and formatters #177
Open
maciekop-l2b
wants to merge
12
commits into
main
Choose a base branch
from
L2B-4977/Logger-refactor
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
e932b93
[L2B-4977] Refactor logger to allow for custom backends and formatters
maciekop-l2b fe029b5
[L2B-4977] Change node version to 18.x in CI
maciekop-l2b 19257a2
[L2B-4977] Fix formatting
maciekop-l2b d8a975a
[L2B-4977] Clear buffer
maciekop-l2b 9e7e9c8
Minor fixes
maciekop-l2b 80f1a6e
Refactor ElasticSearchBackend to make it testable
maciekop-l2b 104e517
Add tests
maciekop-l2b 8dd6eff
Fix lint issues
maciekop-l2b a4cf618
Update docs
maciekop-l2b f18c1b0
Add changeset and gnerate new version
maciekop-l2b 5d376a1
Fix interval issue
maciekop-l2b 2425220
fix formatting
torztomasz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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,4 +1,9 @@ | ||
export * from './env' | ||
export * from './logger/ElasticSearchBackend' | ||
export * from './logger/interfaces' | ||
export * from './logger/LogFormatterEcs' | ||
export * from './logger/LogFormatterJson' | ||
export * from './logger/LogFormatterPretty' | ||
export * from './logger/Logger' | ||
export * from './rate-limit/RateLimiter' | ||
export * from './utils/assert' |
100 changes: 100 additions & 0 deletions
100
packages/backend-tools/src/logger/ElasticSearchBackend.ts
This file contains hidden or 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 |
---|---|---|
@@ -0,0 +1,100 @@ | ||
import { Client } from '@elastic/elasticsearch' | ||
import { v4 as uuidv4 } from 'uuid' | ||
|
||
import { LoggerBackend } from './interfaces' | ||
|
||
export interface ElasticSearchBackendOptions { | ||
node: string | ||
apiKey: string | ||
flushInterval?: number | ||
indexPrefix?: string | ||
} | ||
|
||
export class ElasticSearchBackend implements LoggerBackend { | ||
private readonly options: Required<ElasticSearchBackendOptions> | ||
private readonly buffer: string[] | ||
private readonly client: Client | ||
|
||
constructor(options: ElasticSearchBackendOptions) { | ||
this.options = { | ||
...options, | ||
flushInterval: options.flushInterval ?? 10000, | ||
indexPrefix: options.indexPrefix ?? 'logs', | ||
} | ||
|
||
this.client = new Client({ | ||
node: options.node, | ||
auth: { | ||
apiKey: options.apiKey, | ||
}, | ||
}) | ||
|
||
this.buffer = [] | ||
this.start() | ||
} | ||
|
||
public debug(message: string): void { | ||
this.buffer.push(message) | ||
} | ||
|
||
public log(message: string): void { | ||
this.buffer.push(message) | ||
} | ||
|
||
public warn(message: string): void { | ||
this.buffer.push(message) | ||
} | ||
|
||
public error(message: string): void { | ||
this.buffer.push(message) | ||
} | ||
|
||
private start(): void { | ||
// eslint-disable-next-line @typescript-eslint/no-misused-promises | ||
setInterval(async () => { | ||
await this.flushLogs() | ||
}, this.options.flushInterval) | ||
} | ||
|
||
private async flushLogs(): Promise<void> { | ||
try { | ||
const index = await this.createIndex() | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return | ||
const documents = this.buffer.map((message) => ({ | ||
id: uuidv4(), | ||
...JSON.parse(message), | ||
})) | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return | ||
const operations = documents.flatMap((doc) => [ | ||
{ index: { _index: index } }, | ||
doc, | ||
]) | ||
|
||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return | ||
const bulkResponse = await this.client.bulk({ refresh: true, operations }) | ||
|
||
if (bulkResponse.errors) { | ||
throw new Error('Failed to push liogs to Elastic Search node') | ||
} | ||
} catch (error) { | ||
console.log(error) | ||
} | ||
} | ||
|
||
private async createIndex(): Promise<string> { | ||
const now = new Date() | ||
const indexName = `${ | ||
this.options.indexPrefix | ||
}-${now.getFullYear()}.${now.getMonth()}.${now.getDay()}` | ||
|
||
const exist = await this.client.indices.exists({ index: indexName }) | ||
if (!exist) { | ||
await this.client.indices.create({ | ||
index: indexName, | ||
}) | ||
} | ||
return indexName | ||
} | ||
} |
This file contains hidden or 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 |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import { LogEntry, LogFormatter } from './interfaces' | ||
import { toJSON } from './toJSON' | ||
|
||
// https://www.elastic.co/guide/en/ecs/8.11/ecs-reference.html | ||
export class LogFormatterEcs implements LogFormatter { | ||
public format(entry: LogEntry): string { | ||
const core = { | ||
'@timestamp': entry.time.toISOString(), | ||
log: { | ||
level: entry.level, | ||
}, | ||
service: { | ||
name: entry.service, | ||
}, | ||
message: entry.message, | ||
error: entry.resolvedError | ||
? { | ||
message: entry.resolvedError.error, | ||
type: entry.resolvedError.name, | ||
stack_trace: entry.resolvedError.stack, | ||
} | ||
: undefined, | ||
} | ||
|
||
try { | ||
return toJSON({ ...core, parameters: entry.parameters }) | ||
} catch { | ||
return toJSON({ ...core }) | ||
} | ||
} | ||
} |
This file contains hidden or 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 |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import { LogEntry, LogFormatter } from './interfaces' | ||
import { toJSON } from './toJSON' | ||
|
||
export class LogFormatterJson implements LogFormatter { | ||
public format(entry: LogEntry): string { | ||
const core = { | ||
time: entry.time.toISOString(), | ||
level: entry.level, | ||
service: entry.service, | ||
message: entry.message, | ||
error: entry.resolvedError, | ||
} | ||
|
||
try { | ||
return toJSON({ ...core, parameters: entry.parameters }) | ||
} catch { | ||
return toJSON({ ...core }) | ||
} | ||
} | ||
} |
133 changes: 133 additions & 0 deletions
133
packages/backend-tools/src/logger/LogFormatterPretty.ts
This file contains hidden or 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 |
---|---|---|
@@ -0,0 +1,133 @@ | ||
import chalk from 'chalk' | ||
import { inspect } from 'util' | ||
|
||
import { LogEntry, LogFormatter } from './interfaces' | ||
import { LogLevel } from './LogLevel' | ||
import { toJSON } from './toJSON' | ||
|
||
const STYLES = { | ||
bigint: 'white', | ||
boolean: 'white', | ||
date: 'white', | ||
module: 'white', | ||
name: 'blue', | ||
null: 'white', | ||
number: 'white', | ||
regexp: 'white', | ||
special: 'white', | ||
string: 'white', | ||
symbol: 'white', | ||
undefined: 'white', | ||
} | ||
|
||
const INDENT_SIZE = 4 | ||
const INDENT = ' '.repeat(INDENT_SIZE) | ||
|
||
export class LogFormatterPretty implements LogFormatter { | ||
constructor( | ||
private readonly colors: boolean, | ||
private readonly utc: boolean, | ||
) {} | ||
|
||
public format(entry: LogEntry): string { | ||
const timeOut = this.formatTimePretty(entry.time, this.utc, this.colors) | ||
const levelOut = this.formatLevelPretty(entry.level, this.colors) | ||
const serviceOut = this.formatServicePretty(entry.service, this.colors) | ||
const messageOut = entry.message ? ` ${entry.message}` : '' | ||
const paramsOut = this.formatParametersPretty( | ||
this.sanitize( | ||
entry.resolvedError | ||
? { ...entry.resolvedError, ...entry.parameters } | ||
: entry.parameters ?? {}, | ||
), | ||
this.colors, | ||
) | ||
|
||
return `${timeOut} ${levelOut}${serviceOut}${messageOut}${paramsOut}` | ||
} | ||
|
||
private formatLevelPretty(level: LogLevel, colors: boolean): string { | ||
if (colors) { | ||
switch (level) { | ||
case 'CRITICAL': | ||
case 'ERROR': | ||
return chalk.red(chalk.bold(level.toUpperCase())) | ||
case 'WARN': | ||
return chalk.yellow(chalk.bold(level.toUpperCase())) | ||
case 'INFO': | ||
return chalk.green(chalk.bold(level.toUpperCase())) | ||
case 'DEBUG': | ||
return chalk.magenta(chalk.bold(level.toUpperCase())) | ||
case 'TRACE': | ||
return chalk.gray(chalk.bold(level.toUpperCase())) | ||
} | ||
} | ||
return level.toUpperCase() | ||
} | ||
|
||
private formatTimePretty(now: Date, utc: boolean, colors: boolean): string { | ||
const h = (utc ? now.getUTCHours() : now.getHours()) | ||
.toString() | ||
.padStart(2, '0') | ||
const m = (utc ? now.getUTCMinutes() : now.getMinutes()) | ||
.toString() | ||
.padStart(2, '0') | ||
const s = (utc ? now.getUTCSeconds() : now.getSeconds()) | ||
.toString() | ||
.padStart(2, '0') | ||
const ms = (utc ? now.getUTCMilliseconds() : now.getMilliseconds()) | ||
.toString() | ||
.padStart(3, '0') | ||
|
||
let result = `${h}:${m}:${s}.${ms}` | ||
if (utc) { | ||
result += 'Z' | ||
} | ||
|
||
return colors ? chalk.gray(result) : result | ||
} | ||
|
||
private formatParametersPretty(parameters: object, colors: boolean): string { | ||
const oldStyles = inspect.styles | ||
inspect.styles = STYLES | ||
|
||
const inspected = inspect(parameters, { | ||
colors, | ||
breakLength: 80 - INDENT_SIZE, | ||
depth: 5, | ||
}) | ||
|
||
inspect.styles = oldStyles | ||
|
||
if (inspected === '{}') { | ||
return '' | ||
} | ||
|
||
const indented = inspected | ||
.split('\n') | ||
.map((x) => INDENT + x) | ||
.join('\n') | ||
|
||
if (colors) { | ||
return '\n' + chalk.gray(indented) | ||
} | ||
return '\n' + indented | ||
} | ||
|
||
private formatServicePretty( | ||
service: string | undefined, | ||
colors: boolean, | ||
): string { | ||
if (!service) { | ||
return '' | ||
} | ||
return colors | ||
? ` ${chalk.gray('[')} ${chalk.yellow(service)} ${chalk.gray(']')}` | ||
: ` [ ${service} ]` | ||
} | ||
|
||
private sanitize(parameters: object): object { | ||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return | ||
return JSON.parse(toJSON(parameters)) | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.