
Security News
Axios Maintainer Confirms Social Engineering Attack Behind npm Compromise
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.
@karinjs/log4js
Advanced tools
基于 TypeScript + ESM 完全重写的 log4js,提供更强的类型支持和现代化的 API。这是一个 log4js 的 fork 版本,针对 Node.js 18+ 进行了优化。
npm install @karinjs/log4js
pnpm add @karinjs/log4js
yarn add @karinjs/log4js
import log4js from '@karinjs/log4js'
const logger = log4js.getLogger()
logger.level = 'debug'
logger.debug('这是一条调试日志')
logger.info('这是一条信息日志')
logger.warn('这是一条警告日志')
logger.error('这是一条错误日志')
import log4js from '@karinjs/log4js'
log4js.configure({
appenders: {
console: { type: 'console' },
file: {
type: 'file',
filename: 'logs/app.log',
maxLogSize: 10485760, // 10MB
backups: 3
}
},
categories: {
default: { appenders: ['console', 'file'], level: 'info' }
}
})
const logger = log4js.getLogger('app')
logger.info('Hello, log4js!')
这是相比原版 log4js 的重要增强功能,支持在异步上下文中自动收集和追踪日志。
在一个上下文中运行函数,自动传播上下文 ID,适用于请求追踪、任务追踪等场景。
import log4js from '@karinjs/log4js'
const logger = log4js.getLogger()
const context = logger.runContext(async () => {
logger.info('请求开始')
// 获取当前上下文的唯一 ID
const id = context.id
console.log(`上下文 ID: ${id}`)
// 所有在此上下文中的日志都会被自动收集
logger.debug('处理中...')
logger.info('请求完成')
})
await context.run()
// 自定义清理时间
const context2 = logger.runContext(async () => {
logger.info('这个上下文会在 5 秒后清理')
}, { ms: 5000 })
await context2.run()
获取当前上下文收集的所有日志。
const context = logger.runContext(async () => {
logger.info('日志 1')
logger.warn('日志 2')
logger.error('日志 3')
// 获取当前上下文的所有日志
const logs = context.logs()
console.log('收集到的日志:', logs)
// 输出格式化后的日志数组
})
await context.run()
为上下文日志收集器设置自定义的布局格式。
// 使用 pattern 布局
logger.setContextLayouts('pattern', {
pattern: '%d{yyyy-MM-dd hh:mm:ss} [%p] %c - %m'
})
// 使用 basic 布局(默认)
logger.setContextLayouts('basic')
// 使用 colored 布局
logger.setContextLayouts('colored')
const context = logger.runContext(async () => {
logger.info('这条日志会使用自定义格式')
const logs = context.logs()
// logs 中的日志已经按照设置的 layout 格式化
})
await context.run()
手动销毁指定上下文的日志收集器(通常不需要手动调用)。
const context = logger.runContext(async () => {
const id = logger.contextStore.getStore()?.id
logger.info('一些日志')
// 手动清理(通常不需要,runContext 会自动清理)
if (id) {
logger.destroyContext(id)
}
})
await context.run()
import express from 'express'
import log4js from '@karinjs/log4js'
const app = express()
const logger = log4js.getLogger('http')
app.use(async (req, res, next) => {
const context = logger.runContext(async () => {
const contextId = logger.contextStore.getStore()?.id
logger.info(`[${contextId}] ${req.method} ${req.url}`)
// 在请求处理过程中的所有日志都会被收集
await new Promise<void>((resolve) => {
req.on('end', () => {
// 获取这个请求相关的所有日志
const requestLogs = context.logs()
// 可以将日志发送到监控系统、保存到数据库等
if (res.statusCode >= 400) {
console.error('请求失败,相关日志:', requestLogs)
}
resolve()
})
})
next()
}, { ms: 30000 }) // 30秒后清理
await context.run()
})
async function processTask(taskId: string) {
const context = logger.runContext(async () => {
logger.info(`任务 ${taskId} 开始`)
try {
// 模拟异步操作
await doSomething()
logger.info(`任务 ${taskId} 处理中`)
await doAnotherThing()
logger.info(`任务 ${taskId} 完成`)
} catch (error) {
logger.error(`任务 ${taskId} 失败`, error)
// 任务失败时,获取所有相关日志用于调试
const logs = context.logs()
await saveErrorLogs(taskId, logs)
}
})
await context.run()
}
logger.trace(message, ...args) - 追踪级别日志logger.debug(message, ...args) - 调试级别日志logger.info(message, ...args) - 信息级别日志logger.warn(message, ...args) - 警告级别日志logger.error(message, ...args) - 错误级别日志logger.fatal(message, ...args) - 致命级别日志logger.mark(message, ...args) - 标记级别日志logger.isLevelEnabled(level) - 检查是否启用了指定级别logger.isTraceEnabled() - 是否启用 TRACE 级别logger.isDebugEnabled() - 是否启用 DEBUG 级别logger.isInfoEnabled() - 是否启用 INFO 级别logger.isWarnEnabled() - 是否启用 WARN 级别logger.isErrorEnabled() - 是否启用 ERROR 级别logger.isFatalEnabled() - 是否启用 FATAL 级别logger.addContext(key, value) - 添加上下文信息logger.removeContext(key) - 移除上下文信息logger.clearContext() - 清空上下文信息logger.runContext(fn, options?) - 在上下文中运行函数logger.getContextLogs() - 获取当前上下文的日志logger.setContextLayouts(name, config?) - 设置上下文日志格式logger.destroyContext(id) - 销毁指定上下文支持多种 appender 类型:
console - 控制台输出file - 文件输出dateFile - 按日期滚动的文件输出multiFile - 多文件输出stderr - 标准错误输出stdout - 标准输出支持多种布局格式:
basic - 基础布局colored / coloured - 彩色布局messagePassThrough - 消息透传pattern - 模式布局(支持自定义格式)dummy - 空布局MIT License
本项目基于 log4js-node 进行重写和增强,感谢原作者的贡献。
FAQs
Modern TypeScript ESM version of log4js with Node.js 18+ support
We found that @karinjs/log4js demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.

Security News
The Axios compromise shows how time-dependent dependency resolution makes exposure harder to detect and contain.