Skip to content

Commit

Permalink
feat(logger): logger as functional service
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Feb 15, 2024
1 parent cab9ce1 commit 9d11895
Show file tree
Hide file tree
Showing 8 changed files with 59 additions and 38 deletions.
6 changes: 3 additions & 3 deletions packages/cordis/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as core from '@cordisjs/core'
import * as logger from '@cordisjs/logger'
import { Logger, LoggerService } from '@cordisjs/logger'
import { TimerService } from '@cordisjs/timer'

export * from '@cordisjs/core'
Expand All @@ -26,15 +26,15 @@ export class Context extends core.Context {
this.provide('logger', undefined, true)
this.provide('timer', undefined, true)

this.plugin(logger)
this.plugin(LoggerService)
this.plugin(TimerService)
}
}

export abstract class Service<C extends Context = Context> extends core.Service<C> {
static Context = Context

public logger: logger.Logger
public logger: Logger

constructor(ctx: C | undefined, name: string, options?: boolean | core.Service.Options) {
super(ctx, name, options)
Expand Down
2 changes: 0 additions & 2 deletions packages/cordis/src/worker/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ declare module '@cordisjs/loader' {
}

interface LogLevelConfig {
// a little different from @koishijs/utils
// we don't enforce user to provide a base here
base?: number
[K: string]: LogLevel | undefined
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ export class Context {
while (runtime && !runtime.name) {
runtime = runtime.parent.runtime
}
return runtime?.name
return runtime?.name!
}

get events() {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ export class MainScope<C extends Context = Context> extends EffectScope<C> {
super(registry[Context.current] as C, config)
registry.set(plugin, this)
if (!plugin) {
this.name = 'root'
this.name = 'app'
this.isActive = true
} else {
this.setup()
Expand Down
6 changes: 6 additions & 0 deletions packages/core/tests/associate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ describe('Association', () => {
}

root.provide('foo.bar')
root.provide('foo.baz')
root.plugin(Foo)
expect(root.foo).to.be.instanceof(Foo)
root.foo.qux = 2
Expand All @@ -47,6 +48,11 @@ describe('Association', () => {
expect(root.foo.bar).to.equal(3)
expect(root[`foo.qux`]).to.be.undefined
expect(root[`foo.bar`]).to.equal(3)

root.foo.baz = function () {
return this
}
expect(root.foo.baz()).to.be.instanceof(Foo)
})

test('associated type', async () => {
Expand Down
12 changes: 6 additions & 6 deletions packages/hmr/src/error.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Logger } from 'cordis'
import { Context } from 'cordis'
import { BuildFailure } from 'esbuild'
import { codeFrameColumns } from '@babel/code-frame'
import { readFileSync } from 'fs'
Expand All @@ -7,15 +7,15 @@ function isBuildFailure(e: any): e is BuildFailure {
return Array.isArray(e?.errors) && e.errors.every((error: any) => error.text)
}

export function handleError(e: any, logger: Logger) {
export function handleError(ctx: Context, e: any) {
if (!isBuildFailure(e)) {
logger.warn(e)
ctx.logger.warn(e)
return
}

for (const error of e.errors) {
if (!error.location) {
logger.warn(error.text)
ctx.logger.warn(error.text)
continue
}
try {
Expand All @@ -27,9 +27,9 @@ export function handleError(e: any, logger: Logger) {
highlightCode: true,
message: error.text,
})
logger.warn(`File: ${file}:${line}:${column}\n` + formatted)
ctx.logger.warn(`File: ${file}:${line}:${column}\n` + formatted)
} catch (e) {
logger.warn(e)
ctx.logger.warn(e)
}
}
}
20 changes: 10 additions & 10 deletions packages/hmr/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ interface Reload {
}

class Watcher extends Service {
static name = 'hmr'
static inject = ['loader']

private base: string
Expand Down Expand Up @@ -73,7 +74,6 @@ class Watcher extends Service {
constructor(ctx: Context, private config: Watcher.Config) {
super(ctx, 'hmr')
this.base = resolve(ctx.baseDir, config.base || '')
this.logger = ctx.logger('hmr')
this.initialURL = pathToFileURL(ctx.loader.filename).href
}

Expand Down Expand Up @@ -104,7 +104,7 @@ class Watcher extends Service {
return
}

this.logger.debug('change detected:', path)
this.ctx.logger.debug('change detected:', path)

if (isEntry) {
if (this.ctx.loader.internal!.loadCache.has(filename)) {
Expand Down Expand Up @@ -220,7 +220,7 @@ class Watcher extends Service {
pending.set(job, [plugin, runtime])
this.declined.add(url)
} catch (err) {
this.logger.warn(err)
this.ctx.logger.warn(err)
}
}

Expand Down Expand Up @@ -287,7 +287,7 @@ class Watcher extends Service {
attempts[filename] = this.ctx.loader.unwrapExports(await import(filename))
}
} catch (e) {
handleError(e, this.logger)
handleError(this.ctx, e)
return rollback()
}

Expand All @@ -301,8 +301,8 @@ class Watcher extends Service {
try {
this.ctx.registry.delete(plugin)
} catch (err) {
this.logger.warn('failed to dispose plugin at %c', path)
this.logger.warn(err)
this.ctx.logger.warn('failed to dispose plugin at %c', path)
this.ctx.logger.warn(err)
}

// replace loader cache for `keyFor` method
Expand All @@ -313,10 +313,10 @@ class Watcher extends Service {
const fork = oldFork.parent.plugin(attempts[filename], oldFork.config)
fork.id = oldFork.id
}
this.logger.info('reload plugin at %c', path)
this.ctx.logger.info('reload plugin at %c', path)
} catch (err) {
this.logger.warn('failed to reload plugin at %c', path)
this.logger.warn(err)
this.ctx.logger.warn('failed to reload plugin at %c', path)
this.ctx.logger.warn(err)
throw err
}
}
Expand All @@ -331,7 +331,7 @@ class Watcher extends Service {
fork.id = oldFork.id
}
} catch (err) {
this.logger.warn(err)
this.ctx.logger.warn(err)
}
}
return
Expand Down
47 changes: 32 additions & 15 deletions packages/logger/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Context } from '@cordisjs/core'
import { Context, Service } from '@cordisjs/core'
import Logger from 'reggol'

export { Logger }
Expand All @@ -9,24 +9,41 @@ declare module '@cordisjs/core' {
}
}

interface LoggerService {
export interface LoggerService extends Pick<Logger, Logger.Type | 'extend'> {
(name: string): Logger
}

export function apply(ctx: Context) {
ctx.logger = function (name: string) {
return new Logger(name, { [Context.current]: this })
}
export class LoggerService extends Service {
static name = 'logger'

constructor(ctx: Context) {
super(ctx, 'logger', { immediate: true })

ctx.on('internal/info', function (format, ...args) {
this.logger('app').info(format, ...args)
})

ctx.on('internal/error', function (format, ...args) {
this.logger('app').error(format, ...args)
})

ctx.on('internal/info', function (format, ...args) {
this.logger('app').info(format, ...args)
})
ctx.on('internal/warning', function (format, ...args) {
this.logger('app').warn(format, ...args)
})
}

ctx.on('internal/error', function (format, ...args) {
this.logger('app').error(format, ...args)
})
[Context.invoke](name: string) {
return new Logger(name, { [Context.current]: this })
}

ctx.on('internal/warning', function (format, ...args) {
this.logger('app').warn(format, ...args)
})
static {
for (const type of ['success', 'error', 'info', 'warn', 'debug', 'extend'] as const) {
LoggerService.prototype[type] = function (this: any, ...args: any[]) {
const caller = this[Context.current]
return this(caller.name)[type](...args)
}
}
}
}

export default LoggerService

0 comments on commit 9d11895

Please sign in to comment.