Skip to content

Commit

Permalink
logger: allow to use a custom sink and log level logic
Browse files Browse the repository at this point in the history
  • Loading branch information
eldargab committed Dec 23, 2024
1 parent 8b367b3 commit 8765e37
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 5 deletions.
10 changes: 10 additions & 0 deletions common/changes/@subsquid/logger/master_2024-12-23-14-20.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"changes": [
{
"packageName": "@subsquid/logger",
"comment": "allow to use custom log sink and level determination logic",
"type": "minor"
}
],
"packageName": "@subsquid/logger"
}
35 changes: 31 additions & 4 deletions util/logger/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,44 @@
import {Logger} from "./logger"
import {jsonLinesStderrSink} from "./sinks/json"
import {prettyStderrSink} from "./sinks/pretty"
import {LEVELS, LogLevel} from './level'
import {Logger, Sink} from './logger'
import {jsonLinesStderrSink} from './sinks/json'
import {prettyStderrSink} from './sinks/pretty'


export {LogLevel} from "./level"
export * from "./logger"


/**
* Override the default log level determination logic.
*
* Log levels are cached.
* Call it at the very beginning of the app for it to be effective.
*
* Return `undefined` from the `cb` to fall back to the standard logic.
*/
export function setLogLevelCallback(cb?: (ns: string) => LogLevel | undefined): void {
LEVELS.setLevelCallback(cb)
}


const prettyEnabled = process.env.FORCE_PRETTY_LOGGER ?
process.env.FORCE_PRETTY_LOGGER !== '0' :
process.stderr.isTTY


let ROOT_SINK = prettyEnabled ? prettyStderrSink : jsonLinesStderrSink


/**
* Use custom log sink
*/
export function setRootSink(sink: Sink): void {
ROOT_SINK = sink
}


const ROOT = new Logger(
prettyEnabled ? prettyStderrSink : jsonLinesStderrSink,
rec => ROOT_SINK(rec),
''
)

Expand Down
9 changes: 8 additions & 1 deletion util/logger/src/level.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ function noMatch(ns: string): Specificity {
export class Levels {
private cache: Record<string, LogLevel> = {}
private levels: NamespaceMatcher[] = [noMatch, noMatch, noMatch, noMatch, noMatch, noMatch]
private namespaceLevel?: (ns: string) => LogLevel | undefined

get(ns: string): LogLevel {
let level = this.cache[ns]
Expand All @@ -65,9 +66,15 @@ export class Levels {
}
}

setLevelCallback(cb?: (ns: string) => LogLevel | undefined): void {
this.namespaceLevel = cb
}

private determineLevel(ns: string): LogLevel {
let level = this.namespaceLevel?.(ns)
if (level != null) return level
level = LogLevel.INFO
let specificity = 0
let level = LogLevel.INFO
for (let i = 0; i < this.levels.length; i++) {
let s = this.levels[i](ns)
if (s > specificity) {
Expand Down

0 comments on commit 8765e37

Please sign in to comment.