diff --git a/.env.example b/.env.example index b70e98443..c7cc62f31 100644 --- a/.env.example +++ b/.env.example @@ -19,9 +19,17 @@ API_BASE_URL= PROXY_TARGET_URL= +# console | file | dailyRotateFile LOGGER_TRANSPORT= -LOGGER_LEVEL= LOGGER_BASE_PATH=storage/logs +# error | warn | info | debug +LOGGER_LEVEL= +# If LOGGER_TRANSPORT is dailyRotateFile and using days, add 'd' as the suffix. +LOGGER_MAX_FILES= +# add 'k', 'm', 'g' as the suffix. +LOGGER_MAX_SIZE= +# json | splitter, split by '|' character +LOGGER_FORMAT= ################# DATABASE ################# diff --git a/packages/core/app/src/config/logger.ts b/packages/core/app/src/config/logger.ts index c39c2b9a1..2126abcf9 100644 --- a/packages/core/app/src/config/logger.ts +++ b/packages/core/app/src/config/logger.ts @@ -1,6 +1,12 @@ -import { AppLoggerOptions } from '@nocobase/logger'; +import { AppLoggerOptions, getLoggerLevel, getLoggerTransport } from '@nocobase/logger'; export default { - transports: process.env.LOGGER_TRANSPORT || ['console', 'dailyRotateFile'], - level: process.env.LOGGER_LEVEL || (process.env.APP_ENV === 'development' ? 'debug' : 'info'), + request: { + transports: getLoggerTransport(), + level: getLoggerLevel(), + }, + system: { + transports: getLoggerTransport(), + level: getLoggerLevel(), + }, } as AppLoggerOptions; diff --git a/packages/core/auth/src/auth-manager.ts b/packages/core/auth/src/auth-manager.ts index 518d10eb4..0c8c8e907 100644 --- a/packages/core/auth/src/auth-manager.ts +++ b/packages/core/auth/src/auth-manager.ts @@ -107,7 +107,7 @@ export class AuthManager { ctx.auth = authenticator; } catch (err) { ctx.auth = {} as Auth; - ctx.app.logger.warn(`auth, ${err.message}`); + ctx.logger.warn(err.message, { method: 'check', authenticator: name }); return next(); } if (authenticator) { diff --git a/packages/core/auth/src/base/auth.ts b/packages/core/auth/src/base/auth.ts index eec38f261..b0cb75794 100644 --- a/packages/core/auth/src/base/auth.ts +++ b/packages/core/auth/src/base/auth.ts @@ -66,7 +66,7 @@ export class BaseAuth extends Auth { }), ); } catch (err) { - this.ctx.logger.error(err); + this.ctx.logger.error(err, { method: 'check' }); return null; } } diff --git a/packages/core/client/src/schema-component/antd/association-field/InternalViewer.tsx b/packages/core/client/src/schema-component/antd/association-field/InternalViewer.tsx index be92223bd..9f90c9d24 100644 --- a/packages/core/client/src/schema-component/antd/association-field/InternalViewer.tsx +++ b/packages/core/client/src/schema-component/antd/association-field/InternalViewer.tsx @@ -54,8 +54,8 @@ export const ReadPrettyInternalViewer: React.FC = observer( .map((o) => o?.[fieldNames?.label || 'label']) .join(' / ') : isObject(value) - ? JSON.stringify(value) - : value; + ? JSON.stringify(value) + : value; const val = toValue(compile(label), 'N/A'); const labelUiSchema = useLabelUiSchema( record?.__collection || collectionField?.target, diff --git a/packages/core/client/src/schema-component/antd/expand-action/Expand.Action.Design.tsx b/packages/core/client/src/schema-component/antd/expand-action/Expand.Action.Design.tsx index 69ac4d311..b089332a3 100644 --- a/packages/core/client/src/schema-component/antd/expand-action/Expand.Action.Design.tsx +++ b/packages/core/client/src/schema-component/antd/expand-action/Expand.Action.Design.tsx @@ -56,8 +56,8 @@ export const ExpandActionDesign = (props) => { default: fieldSchema?.['x-component-props']?.danger ? 'danger' : fieldSchema?.['x-component-props']?.type === 'primary' - ? 'primary' - : 'default', + ? 'primary' + : 'default', enum: [ { value: 'default', label: '{{t("Default")}}' }, { value: 'primary', label: '{{t("Highlight")}}' }, diff --git a/packages/core/database/src/database.ts b/packages/core/database/src/database.ts index 257b3fdcc..0e85d304a 100644 --- a/packages/core/database/src/database.ts +++ b/packages/core/database/src/database.ts @@ -1,4 +1,4 @@ -import { Logger } from '@nocobase/logger'; +import { Logger, LoggerOptions, createConsoleLogger, createLogger } from '@nocobase/logger'; import { applyMixins, AsyncEmitter } from '@nocobase/utils'; import merge from 'deepmerge'; import { EventEmitter } from 'events'; @@ -92,6 +92,7 @@ export interface IDatabaseOptions extends Options { migrator?: any; usingBigIntForId?: boolean; underscored?: boolean; + logger?: LoggerOptions | Logger; customHooks?: any; instanceId?: string; } @@ -218,6 +219,16 @@ export class Database extends EventEmitter implements AsyncEmitter { ...lodash.clone(options), }; + if (options.logger) { + if (typeof options.logger['log'] === 'function') { + this.logger = options.logger as Logger; + } else { + this.logger = createLogger(options.logger); + } + } else { + this.logger = createConsoleLogger(); + } + if (!options.instanceId) { this._instanceId = nanoid(); } else { @@ -240,6 +251,7 @@ export class Database extends EventEmitter implements AsyncEmitter { // https://github.com/sequelize/sequelize/issues/1774 require('pg').defaults.parseInt8 = true; } + this.options = opts; const sequelizeOptions = this.sequelizeOptions(this.options); @@ -348,10 +360,6 @@ export class Database extends EventEmitter implements AsyncEmitter { this.context = context; } - setLogger(logger: Logger) { - this.logger = logger; - } - sequelizeOptions(options) { if (options.dialect === 'postgres') { if (!options.hooks) { @@ -757,11 +765,13 @@ export class Database extends EventEmitter implements AsyncEmitter { const authenticate = async () => { try { await this.sequelize.authenticate(others); - console.log('Connection has been established successfully.'); + this.logger.info('Connection has been established successfully.', { method: 'auth' }); } catch (error) { - console.log(`Attempt ${attemptNumber}/${retry}: Unable to connect to the database: ${error.message}`); + this.logger.warn(`Attempt ${attemptNumber}/${retry}: Unable to connect to the database: ${error.message}`, { + method: 'auth', + }); const nextDelay = startingDelay * Math.pow(timeMultiple, attemptNumber - 1); - console.log(`Will retry in ${nextDelay}ms...`); + this.logger.warn(`Will retry in ${nextDelay}ms...`, { method: 'auth' }); attemptNumber++; throw error; // Re-throw the error so that backoff can catch and handle it } diff --git a/packages/core/logger/package.json b/packages/core/logger/package.json index 35e2b642f..1526e8b0b 100644 --- a/packages/core/logger/package.json +++ b/packages/core/logger/package.json @@ -8,11 +8,14 @@ "repository": { "type": "git", "url": "git+https://github.com/nocobase/nocobase.git", - "directory": "packages/logging" + "directory": "packages/logger" }, "dependencies": { + "chalk": "^4", "lodash": "^4.17.21", + "triple-beam": "^1.4.1", "winston": "^3.8.2", - "winston-daily-rotate-file": "^4.7.1" + "winston-daily-rotate-file": "^4.7.1", + "winston-transport": "^4.5.0" } } diff --git a/packages/core/logger/src/app-logger.ts b/packages/core/logger/src/app-logger.ts new file mode 100644 index 000000000..82355cf4e --- /dev/null +++ b/packages/core/logger/src/app-logger.ts @@ -0,0 +1,23 @@ +import { Logger } from 'winston'; +import { SystemLoggerOptions, createSystemLogger } from './system-logger'; +import { getLoggerFilePath } from './config'; + +export const createAppLogger = ({ app, ...options }: SystemLoggerOptions & { app?: string }) => + createSystemLogger({ dirname: getLoggerFilePath(app), filename: 'system', seperateError: true, ...options }); + +export type logMethod = ( + message: string, + meta?: { + module?: string; + submodule?: string; + method?: string; + [key: string]: any; + }, +) => AppLogger; + +export interface AppLogger extends Omit { + info: logMethod; + warn: logMethod; + error: logMethod; + debug: logMethod; +} diff --git a/packages/core/logger/src/config.ts b/packages/core/logger/src/config.ts new file mode 100644 index 000000000..aeaa67e02 --- /dev/null +++ b/packages/core/logger/src/config.ts @@ -0,0 +1,17 @@ +import path from 'path'; + +export const getLoggerLevel = () => + process.env.LOGGER_LEVEL || (process.env.APP_ENV === 'development' ? 'debug' : 'info'); + +export const getLoggerFilePath = (...paths: string[]): string => { + return path.resolve(process.env.LOGGER_BASE_PATH || path.resolve(process.cwd(), 'storage', 'logs'), ...paths); +}; + +export const getLoggerTransport = (): ('console' | 'file' | 'dailyRotateFile')[] => + ( + (process.env.LOGGER_TRANSPORT as any) || + (process.env.APP_ENV === 'development' ? 'console' : 'console,dailyRotateFile') + ).split(','); + +export const getLoggerFormat = (): 'logfmt' | 'json' | 'delimiter' => + (process.env.LOGGER_FORMAT as any) || (process.env.APP_ENV === 'development' ? 'logfmt' : 'json'); diff --git a/packages/core/logger/src/create-app-logger.ts b/packages/core/logger/src/deprecated/create-app-logger.ts similarity index 100% rename from packages/core/logger/src/create-app-logger.ts rename to packages/core/logger/src/deprecated/create-app-logger.ts diff --git a/packages/core/logger/src/create-logger.ts b/packages/core/logger/src/deprecated/create-logger.ts similarity index 99% rename from packages/core/logger/src/create-logger.ts rename to packages/core/logger/src/deprecated/create-logger.ts index ff376f15d..dff3d170c 100644 --- a/packages/core/logger/src/create-logger.ts +++ b/packages/core/logger/src/deprecated/create-logger.ts @@ -48,6 +48,7 @@ interface LoggerOptions extends Omit { transports?: WinstonTransport; } +// @deprecated function createLogger(options: LoggerOptions = {}) { const transports: winston.transport[] = toArr(options?.transports || ['console', 'dailyRotateFile']) .map((t) => { diff --git a/packages/core/logger/src/format.ts b/packages/core/logger/src/format.ts new file mode 100644 index 000000000..d1870350b --- /dev/null +++ b/packages/core/logger/src/format.ts @@ -0,0 +1,106 @@ +import chalk from 'chalk'; +import winston from 'winston'; +import { getLoggerFormat } from './config'; +import { LoggerOptions } from './logger'; + +const DEFAULT_DELIMITER = '|'; + +const colorize = { + errors: chalk.red, + module: chalk.cyan, + reqId: chalk.gray, + request: chalk.green, +}; + +export const getFormat = (format?: LoggerOptions['format']) => { + const configFormat = format || getLoggerFormat(); + let logFormat: winston.Logform.Format; + switch (configFormat) { + case 'logfmt': + logFormat = logfmtFormat; + break; + case 'delimiter': + logFormat = winston.format.combine(escapeFormat, delimiterFormat); + break; + case 'json': + logFormat = winston.format.combine(stripColorFormat, winston.format.json({ deterministic: false })); + break; + default: + return winston.format.combine(stripColorFormat, format as winston.Logform.Format); + } + return winston.format.combine(sortFormat, logFormat); +}; + +export const colorFormat: winston.Logform.Format = winston.format((info) => { + Object.entries(info).forEach(([k, v]) => { + if (k === 'message' && info['level'].includes('error')) { + info[k] = colorize.errors(v); + } + if (k === 'reqId' && v) { + info[k] = colorize.reqId(v); + } + if ((k === 'module' || k === 'submodule') && v) { + info[k] = colorize.module(v); + } + if (v === 'request' || v === 'response') { + info[k] = colorize.request(v); + } + }); + return info; +})(); + +export const stripColorFormat: winston.Logform.Format = winston.format((info) => { + Object.entries(info).forEach(([k, v]) => { + if (typeof v !== 'string') { + return; + } + const regex = new RegExp(`\\x1b\\[\\d+m`, 'g'); + info[k] = v.replace(regex, ''); + }); + return info; +})(); + +// https://brandur.org/logfmt +export const logfmtFormat: winston.Logform.Format = winston.format.printf((info) => + Object.entries(info) + .map(([k, v]) => { + if (typeof v === 'object') { + try { + v = JSON.stringify(v); + } catch (error) { + v = String(v); + } + } + if (v === undefined || v === null) { + v = ''; + } + return `${k}=${v}`; + }) + .join(' '), +); + +export const delimiterFormat = winston.format.printf((info) => + Object.entries(info) + .map(([, v]) => { + if (typeof v === 'object') { + try { + return JSON.stringify(v); + } catch (error) { + return String(v); + } + } + return v; + }) + .join(DEFAULT_DELIMITER), +); + +export const escapeFormat: winston.Logform.Format = winston.format((info) => { + let { message } = info; + if (typeof message === 'string' && message.includes(DEFAULT_DELIMITER)) { + message = message.replace(/"/g, '\\"'); + message = `"${message}"`; + } + return { ...info, message }; +})(); + +export const sortFormat = winston.format((info) => ({ level: info.level, timestamp: info.timestamp, ...info }))(); diff --git a/packages/core/logger/src/index.ts b/packages/core/logger/src/index.ts index b0d7af6c2..cd31685b8 100644 --- a/packages/core/logger/src/index.ts +++ b/packages/core/logger/src/index.ts @@ -1,2 +1,6 @@ -export * from './create-app-logger'; -export * from './create-logger'; +export * from './config'; +export * from './logger'; +export * from './system-logger'; +export * from './request-logger'; +export * from './app-logger'; +export * from './transports'; diff --git a/packages/core/logger/src/logger.ts b/packages/core/logger/src/logger.ts new file mode 100644 index 000000000..9218d2981 --- /dev/null +++ b/packages/core/logger/src/logger.ts @@ -0,0 +1,53 @@ +import winston, { Logger } from 'winston'; +import { SystemLoggerOptions } from './system-logger'; +import 'winston-daily-rotate-file'; +import { getLoggerLevel } from './config'; +import { getTransports } from './transports'; +import { colorFormat, logfmtFormat, sortFormat } from './format'; + +interface LoggerOptions extends Omit { + dirname?: string; + filename?: string; + format?: 'logfmt' | 'json' | 'delimiter' | winston.Logform.Format; + transports?: ('console' | 'file' | 'dailyRotateFile' | winston.transport)[]; +} + +export const createLogger = (options: LoggerOptions) => { + if (process.env.GITHUB_ACTIONS) { + return createConsoleLogger(); + } + const { format, ...rest } = options; + const winstonOptions = { + level: getLoggerLevel(), + ...rest, + transports: getTransports(options), + }; + return winston.createLogger(winstonOptions); +}; + +export const createConsoleLogger = (options?: winston.LoggerOptions) => { + const { format, ...rest } = options || {}; + return winston.createLogger({ + level: getLoggerLevel(), + format: winston.format.combine( + winston.format.timestamp({ + format: 'YYYY-MM-DD HH:mm:ss', + }), + format || winston.format.combine(sortFormat, colorFormat, logfmtFormat), + ), + ...(rest || {}), + transports: [new winston.transports.Console()], + }); +}; + +export { Logger, LoggerOptions }; +interface ReqeustLoggerOptions extends LoggerOptions { + skip?: (ctx?: any) => Promise; + requestWhitelist?: string[]; + responseWhitelist?: string[]; +} + +export interface AppLoggerOptions { + request: ReqeustLoggerOptions; + system: SystemLoggerOptions; +} diff --git a/packages/core/logger/src/request-logger.ts b/packages/core/logger/src/request-logger.ts new file mode 100644 index 000000000..372421711 --- /dev/null +++ b/packages/core/logger/src/request-logger.ts @@ -0,0 +1,71 @@ +import { getLoggerFilePath } from './config'; +import { AppLoggerOptions, createLogger } from './logger'; +import { pick } from 'lodash'; +const defaultRequestWhitelist = [ + 'action', + 'header.x-role', + 'header.x-hostname', + 'header.x-timezone', + 'header.x-locale', + 'referer', +]; +const defaultResponseWhitelist = ['status']; + +export const requestLogger = (appName: string, options?: AppLoggerOptions) => { + const requestLogger = createLogger({ + dirname: getLoggerFilePath(appName), + filename: 'request', + ...(options?.request || {}), + }); + return async (ctx, next) => { + const reqId = ctx.reqId; + const path = /^\/api\/(.+):(.+)/.exec(ctx.path); + const contextLogger = ctx.app.log.child({ reqId, module: path?.[1], submodule: path?.[2] }); + // ctx.reqId = reqId; + ctx.logger = ctx.log = contextLogger; + const startTime = Date.now(); + const requestInfo = { + method: ctx.method, + path: ctx.url, + }; + requestLogger.info({ + reqId, + message: 'request', + ...requestInfo, + req: pick(ctx.request.toJSON(), options?.request?.requestWhitelist || defaultRequestWhitelist), + action: ctx.action?.toJSON?.(), + }); + let error: Error; + try { + await next(); + } catch (e) { + error = e; + } finally { + const cost = Date.now() - startTime; + const status = ctx.status; + const info = { + reqId, + message: 'response', + ...requestInfo, + res: pick(ctx.response.toJSON(), options?.request?.responseWhitelist || defaultResponseWhitelist), + action: ctx.action?.toJSON?.(), + userId: ctx.auth?.user?.id, + status: ctx.status, + cost, + }; + if (Math.floor(status / 100) == 5) { + requestLogger.error({ ...info, res: ctx.body?.['errors'] || ctx.body }); + } else if (Math.floor(status / 100) == 4) { + requestLogger.warn({ ...info, res: ctx.body?.['errors'] || ctx.body }); + } else { + requestLogger.info(info); + } + } + + ctx.res.setHeader('X-Request-Id', reqId); + + if (error) { + throw error; + } + }; +}; diff --git a/packages/core/logger/src/system-logger.ts b/packages/core/logger/src/system-logger.ts new file mode 100644 index 000000000..5c2cd4fd1 --- /dev/null +++ b/packages/core/logger/src/system-logger.ts @@ -0,0 +1,54 @@ +import winston, { format } from 'winston'; +import { LoggerOptions, createLogger } from './logger'; +import Transport from 'winston-transport'; +import { SPLAT } from 'triple-beam'; +import { getFormat } from './format'; + +export interface SystemLoggerOptions extends LoggerOptions { + seperateError?: boolean; // print error seperately, default true +} + +class SystemLoggerTransport extends Transport { + private logger: winston.Logger; + private errorLogger: winston.Logger; + + constructor({ seperateError, filename, ...options }: SystemLoggerOptions) { + super({ ...options, format: null }); + this.logger = createLogger({ + ...options, + filename, + format: winston.format.combine( + format((info) => (seperateError && info.level === 'error' ? false : info))(), + getFormat(options.format), + ), + }); + if (seperateError) { + this.errorLogger = createLogger({ + ...options, + filename: `${filename}_error`, + level: 'error', + }); + } + } + + log(info: any, callback: any) { + const { level, message, reqId, [SPLAT]: args } = info; + const logger = level === 'error' && this.errorLogger ? this.errorLogger : this.logger; + const { module, submodule, method, ...meta } = args?.[0] || {}; + logger.log({ + level, + reqId, + message, + module: module || info['module'] || '', + submodule: submodule || info['submodule'] || '', + method: method || '', + meta, + }); + callback(null, true); + } +} + +export const createSystemLogger = (options: SystemLoggerOptions) => + winston.createLogger({ + transports: [new SystemLoggerTransport(options)], + }); diff --git a/packages/core/logger/src/transports.ts b/packages/core/logger/src/transports.ts new file mode 100644 index 000000000..6a3899d8e --- /dev/null +++ b/packages/core/logger/src/transports.ts @@ -0,0 +1,57 @@ +import winston from 'winston'; +import { DailyRotateFileTransportOptions } from 'winston-daily-rotate-file'; +import { LoggerOptions } from './logger'; +import { getLoggerFilePath, getLoggerFormat, getLoggerTransport } from './config'; +import path from 'path'; +import { colorFormat, getFormat } from './format'; + +export const Transports = { + console: (options?: winston.transports.ConsoleTransportOptions) => new winston.transports.Console(options), + file: (options?: winston.transports.FileTransportOptions) => + new winston.transports.File({ + maxsize: Number(process.env.LOGGER_MAX_SIZE) || 1024 * 1024 * 20, + maxFiles: Number(process.env.LOGGER_MAX_FILES) || 10, + ...options, + }), + dailyRotateFile: (options?: DailyRotateFileTransportOptions) => + new winston.transports.DailyRotateFile({ + maxSize: Number(process.env.LOGGER_MAX_SIZE), + maxFiles: Number(process.env.LOGGER_MAX_FILES) || '14d', + ...options, + }), +}; + +export const getTransports = (options: LoggerOptions) => { + const { filename, format: _format, transports: _transports } = options; + let { dirname } = options; + const configTransports = _transports || getLoggerTransport(); + const configFormat = _format || getLoggerFormat(); + dirname = dirname || getLoggerFilePath(); + if (!path.isAbsolute(dirname)) { + dirname = path.resolve(process.cwd(), dirname); + } + const format = winston.format.combine( + winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), + getFormat(configFormat), + ); + + const transports = { + console: () => + Transports.console({ + format: winston.format.combine(winston.format.colorize(), colorFormat, format), + }), + file: () => + Transports.file({ + dirname, + filename: filename.includes('.log') ? filename : `${filename}.log`, + format, + }), + dailyRotateFile: () => + Transports.dailyRotateFile({ + dirname, + filename: filename.includes('%DATE%') || filename.includes('.log') ? filename : `${filename}_%DATE%.log`, + format, + }), + }; + return configTransports?.map((t) => (typeof t === 'string' ? transports[t]() : t)) || transports['console'](); +}; diff --git a/packages/core/server/src/app-supervisor.ts b/packages/core/server/src/app-supervisor.ts index cefbf1235..1f20da23b 100644 --- a/packages/core/server/src/app-supervisor.ts +++ b/packages/core/server/src/app-supervisor.ts @@ -178,6 +178,8 @@ export class AppSupervisor extends EventEmitter implements AsyncEmitter { throw new Error(`app ${app.name} already exists`); } + app.logger.info(`add app ${app.name} into supervisor`, { submodule: 'supervisor', method: 'addApp' }); + this.bindAppEvents(app); this.apps[app.name] = app; diff --git a/packages/core/server/src/application.ts b/packages/core/server/src/application.ts index 23380b86c..c379f26bb 100644 --- a/packages/core/server/src/application.ts +++ b/packages/core/server/src/application.ts @@ -3,8 +3,15 @@ import { registerActions } from '@nocobase/actions'; import { actions as authActions, AuthManager, AuthManagerOptions } from '@nocobase/auth'; import { Cache, CacheManager, CacheManagerOptions } from '@nocobase/cache'; import Database, { CollectionOptions, IDatabaseOptions } from '@nocobase/database'; -import { AppLoggerOptions, createAppLogger, Logger } from '@nocobase/logger'; -import { ResourceOptions, Resourcer } from '@nocobase/resourcer'; +import { + AppLoggerOptions, + createLogger, + createAppLogger, + AppLogger, + LoggerOptions, + getLoggerFilePath, +} from '@nocobase/logger'; +import { Resourcer, ResourceOptions } from '@nocobase/resourcer'; import { applyMixins, AsyncEmitter, measureExecutionTime, Toposort, ToposortOptions } from '@nocobase/utils'; import { Command, CommandOptions, ParseOptions } from 'commander'; import { IncomingMessage, Server, ServerResponse } from 'http'; @@ -31,9 +38,11 @@ import { ApplicationVersion } from './helpers/application-version'; import { Locale } from './locale'; import { Plugin } from './plugin'; import { InstallOptions, PluginManager } from './plugin-manager'; +import { randomUUID } from 'crypto'; import packageJson from '../package.json'; import chalk from 'chalk'; import { RecordableHistogram, performance } from 'node:perf_hooks'; +import path from 'path'; export type PluginType = string | typeof Plugin; export type PluginConfiguration = PluginType | [PluginType, any]; @@ -135,6 +144,7 @@ export class Application exten constructor(public options: ApplicationOptions) { super(); + this.context.reqId = randomUUID(); this.rawOptions = this.name == 'main' ? lodash.cloneDeep(options) : {}; this.init(); @@ -165,7 +175,7 @@ export class Application exten return this._db; } - protected _logger: Logger; + protected _logger: AppLogger; get logger() { return this._logger; @@ -282,7 +292,7 @@ export class Application exten } plugin(pluginClass: any, options?: O) { - this.log.debug(`add plugin ${pluginClass.name}`); + this.log.debug(`add plugin`, { method: 'plugin', name: pluginClass.name }); this.pm.addPreset(pluginClass, options); } @@ -335,7 +345,7 @@ export class Application exten if (options?.reload) { this.setMaintainingMessage('app reload'); - this.log.info(`app.reload()`); + this.log.info(`app.reload()`, { method: 'load' }); const oldDb = this._db; this.init(); if (!oldDb.closed()) { @@ -364,7 +374,7 @@ export class Application exten } async reload(options?: any) { - this.log.debug(`start reload`); + this.log.debug(`start reload`, { method: 'reload' }); this._loaded = false; @@ -375,10 +385,10 @@ export class Application exten reload: true, }); - this.log.debug('emit afterReload'); + this.log.debug('emit afterReload', { method: 'reload' }); this.setMaintainingMessage('emit afterReload'); await this.emitAsync('afterReload', this, options); - this.log.debug(`finish reload`); + this.log.debug(`finish reload`, { method: 'reload' }); } getPlugin

(name: string | typeof Plugin) { @@ -438,11 +448,14 @@ export class Application exten return command; } - async runAsCLI(argv = process.argv, options?: ParseOptions & { throwError?: boolean }) { + async runAsCLI(argv = process.argv, options?: ParseOptions & { throwError?: boolean; reqId?: string }) { if (this.activatedCommand) { return; } - + if (options.reqId) { + this.context.reqId = options.reqId; + this._logger = this._logger.child({ reqId: this.context.reqId }); + } this._maintainingStatusBeforeCommand = this._maintainingCommandStatus; try { @@ -548,11 +561,11 @@ export class Application exten } async stop(options: any = {}) { - this.log.debug('stop app...'); + this.log.debug('stop app...', { method: 'stop' }); this.setMaintainingMessage('stopping app...'); if (this.stopped) { - this.log.warn(`Application ${this.name} already stopped`); + this.log.warn(`Application ${this.name} already stopped`, { method: 'stop' }); return; } @@ -562,11 +575,11 @@ export class Application exten // close database connection // silent if database already closed if (!this.db.closed()) { - this.logger.info(`close db`); + this.log.info(`close db`, { method: 'stop' }); await this.db.close(); } } catch (e) { - this.log.error(e); + this.log.error(e.message, { method: 'stop', err: e.stack }); } if (this._cacheManager) { @@ -576,20 +589,20 @@ export class Application exten await this.emitAsync('afterStop', this, options); this.stopped = true; - this.log.info(`${this.name} is stopped`); + this.log.info(`${this.name} is stopped`, { method: 'stop' }); this._started = false; } async destroy(options: any = {}) { - this.logger.debug('start destroy app'); + this.log.debug('start destroy app', { method: 'destory' }); this.setMaintainingMessage('destroying app...'); await this.emitAsync('beforeDestroy', this, options); await this.stop(options); - this.logger.debug('emit afterDestroy'); + this.log.debug('emit afterDestroy', { method: 'destory' }); await this.emitAsync('afterDestroy', this, options); - this.logger.debug('finish destroy app'); + this.log.debug('finish destroy app', { method: 'destory' }); } async isInstalled() { @@ -600,26 +613,26 @@ export class Application exten async install(options: InstallOptions = {}) { this.setMaintainingMessage('installing app...'); - this.log.debug('Database dialect: ' + this.db.sequelize.getDialect()); + this.log.debug('Database dialect: ' + this.db.sequelize.getDialect(), { method: 'install' }); if (options?.clean || options?.sync?.force) { - this.log.debug('truncate database'); + this.log.debug('truncate database', { method: 'install' }); await this.db.clean({ drop: true }); - this.log.debug('app reloading'); + this.log.debug('app reloading', { method: 'install' }); await this.reload(); } else if (await this.isInstalled()) { - this.log.warn('app is installed'); + this.log.warn('app is installed', { method: 'install' }); return; } - this.log.debug('emit beforeInstall'); + this.log.debug('emit beforeInstall', { method: 'install' }); this.setMaintainingMessage('call beforeInstall hook...'); await this.emitAsync('beforeInstall', this, options); - this.log.debug('start install plugins'); + this.log.debug('start install plugins', { method: 'install' }); await this.pm.install(options); - this.log.debug('update version'); + this.log.debug('update version', { method: 'install' }); await this.version.update(); - this.log.debug('emit afterInstall'); + this.log.debug('emit afterInstall', { method: 'install' }); this.setMaintainingMessage('call afterInstall hook...'); await this.emitAsync('afterInstall', this, options); @@ -678,18 +691,25 @@ export class Application exten } } + createLogger(options: LoggerOptions) { + const { dirname } = options; + return createLogger({ + ...options, + dirname: getLoggerFilePath(this.name || 'main', dirname || ''), + }); + } + protected init() { const options = this.options; - const logger = createAppLogger({ - ...options.logger, - defaultMeta: { - app: this.name, - }, + this._logger = createAppLogger({ + app: this.name, + ...(options.logger?.system || {}), + }).child({ + reqId: this.context.reqId, + module: 'application', }); - this._logger = logger.instance; - this.reInitEvents(); this.middleware = new Toposort(); @@ -698,8 +718,6 @@ export class Application exten this._cronJobManager = new CronJobManager(this); - this.use(logger.middleware, { tag: 'logger' }); - if (this._db) { // MaxListenersExceededWarning this._db.removeAllListeners(); @@ -711,7 +729,7 @@ export class Application exten this._cli = this.createCli(); this._i18n = createI18n(options); this.context.db = this._db; - this.context.logger = this._logger; + // this.context.logger = this._logger; this.context.resourcer = this._resourcer; this.context.cacheManager = this._cacheManager; this.context.cache = this._cache; @@ -758,15 +776,28 @@ export class Application exten } protected createDatabase(options: ApplicationOptions) { + const sqlLogger = this.createLogger({ + filename: 'sql', + level: 'debug', + }); + const logging = (msg: any) => { + if (typeof msg === 'string') { + msg = msg.replace(/[\r\n]/gm, '').replace(/\s+/g, ' '); + } + if (msg.includes('INSERT INTO')) { + msg = msg.substring(0, 2000) + '...'; + } + sqlLogger.debug({ reqId: this.context.reqId, message: msg }); + }; + const dbOptions = options.database instanceof Database ? options.database.options : options.database; const db = new Database({ - ...(options.database instanceof Database ? options.database.options : options.database), + ...dbOptions, + logging: dbOptions.logging ? logging : false, migrator: { context: { app: this }, }, + logger: this._logger.child({ module: 'database' }), }); - - db.setLogger(this._logger); - return db; } } diff --git a/packages/core/server/src/gateway/index.ts b/packages/core/server/src/gateway/index.ts index db3ab86cd..ec3da5206 100644 --- a/packages/core/server/src/gateway/index.ts +++ b/packages/core/server/src/gateway/index.ts @@ -19,6 +19,8 @@ import { applyErrorWithArgs, getErrorWithCode } from './errors'; import { IPCSocketClient } from './ipc-socket-client'; import { IPCSocketServer } from './ipc-socket-server'; import { WSServer } from './ws-server'; +import { createLogger } from '@nocobase/logger'; +import { randomUUID } from 'crypto'; const compress = promisify(compression()); @@ -124,6 +126,13 @@ export class Gateway extends EventEmitter { this.emit('appSelectorChanged'); } + async logger(req: IncomingRequest) { + const reqId = randomUUID(); + const appName = await this.getRequestHandleAppName(req); + req.headers['reqId'] = reqId; + return createLogger({ filename: `${appName}_request` }).child({ reqId }); + } + responseError( res: ServerResponse, error: { diff --git a/packages/core/server/src/gateway/ipc-socket-client.ts b/packages/core/server/src/gateway/ipc-socket-client.ts index 8da38ca1a..970c9c981 100644 --- a/packages/core/server/src/gateway/ipc-socket-client.ts +++ b/packages/core/server/src/gateway/ipc-socket-client.ts @@ -1,5 +1,6 @@ import net from 'net'; import * as events from 'events'; +import { Logger, createConsoleLogger } from '@nocobase/logger'; export const writeJSON = (socket: net.Socket, data: object) => { socket.write(JSON.stringify(data) + '\n', 'utf8'); @@ -7,9 +8,11 @@ export const writeJSON = (socket: net.Socket, data: object) => { export class IPCSocketClient extends events.EventEmitter { client: net.Socket; + logger: Logger; constructor(client: net.Socket) { super(); + this.logger = createConsoleLogger(); this.client = client; @@ -41,20 +44,20 @@ export class IPCSocketClient extends events.EventEmitter { }); } - async handleServerMessage({ type, payload }) { + async handleServerMessage({ reqId, type, payload }) { switch (type) { case 'error': - console.error(payload.message); + this.logger.error({ reqId, message: `${payload.message}|${payload.stack}` }); break; case 'success': - console.log('success'); + this.logger.info({ reqId, message: 'success' }); break; default: - console.log({ type, payload }); + this.logger.info({ reqId, message: JSON.stringify({ type, payload }) }); break; } - this.emit('response', { type, payload }); + this.emit('response', { reqId, type, payload }); } close() { diff --git a/packages/core/server/src/gateway/ipc-socket-server.ts b/packages/core/server/src/gateway/ipc-socket-server.ts index 07e955605..b41c73ab6 100644 --- a/packages/core/server/src/gateway/ipc-socket-server.ts +++ b/packages/core/server/src/gateway/ipc-socket-server.ts @@ -2,6 +2,7 @@ import net from 'net'; import fs from 'fs'; import { AppSupervisor } from '../app-supervisor'; import { writeJSON } from './ipc-socket-client'; +import { randomUUID } from 'crypto'; export class IPCSocketServer { socketServer: net.Server; @@ -32,19 +33,23 @@ export class IPCSocketServer { continue; } + const reqId = randomUUID(); const dataObj = JSON.parse(message); - IPCSocketServer.handleClientMessage(dataObj) + IPCSocketServer.handleClientMessage({ reqId, ...dataObj }) .then(() => { writeJSON(c, { + reqId, type: 'success', }); }) .catch((err) => { writeJSON(c, { + reqId, type: 'error', payload: { message: err.message, + stack: err.stack, }, }); }); @@ -59,7 +64,7 @@ export class IPCSocketServer { return new IPCSocketServer(socketServer); } - static async handleClientMessage({ type, payload }) { + static async handleClientMessage({ reqId, type, payload }) { console.log(`cli received message ${type}`); if (type === 'passCliArgv') { @@ -76,6 +81,7 @@ export class IPCSocketServer { } return mainApp.runAsCLI(argv, { + reqId, from: 'node', throwError: true, }); diff --git a/packages/core/server/src/gateway/ws-server.ts b/packages/core/server/src/gateway/ws-server.ts index 3c0d18429..c50808d9c 100644 --- a/packages/core/server/src/gateway/ws-server.ts +++ b/packages/core/server/src/gateway/ws-server.ts @@ -5,6 +5,7 @@ import { IncomingMessage } from 'http'; import { AppSupervisor } from '../app-supervisor'; import { applyErrorWithArgs, getErrorWithCode } from './errors'; import lodash from 'lodash'; +import { Logger } from '@nocobase/logger'; declare class WebSocketWithId extends WebSocket { id: string; @@ -26,6 +27,7 @@ function getPayloadByErrorCode(code, options) { export class WSServer { wss: WebSocket.Server; webSocketClients = new Map(); + logger: Logger; constructor() { this.wss = new WebSocketServer({ noServer: true }); diff --git a/packages/core/server/src/helper.ts b/packages/core/server/src/helper.ts index 0d78349ed..f3cca7342 100644 --- a/packages/core/server/src/helper.ts +++ b/packages/core/server/src/helper.ts @@ -13,6 +13,8 @@ import { dateTemplate } from './middlewares/data-template'; import { dataWrapping } from './middlewares/data-wrapping'; import { db2resource } from './middlewares/db2resource'; import { i18n } from './middlewares/i18n'; +import { requestLogger } from '@nocobase/logger'; +import { randomUUID } from 'crypto'; import { createHistogram, RecordableHistogram } from 'perf_hooks'; export function createI18n(options: ApplicationOptions) { @@ -40,6 +42,11 @@ export function createResourcer(options: ApplicationOptions) { } export function registerMiddlewares(app: Application, options: ApplicationOptions) { + app.use(async (ctx, next) => { + app.context.reqId = randomUUID(); + await next(); + }); + app.use(requestLogger(app.name, options.logger), { tag: 'logger' }); app.use( cors({ exposeHeaders: ['content-disposition'], diff --git a/packages/core/server/src/locale/locale.ts b/packages/core/server/src/locale/locale.ts index 457c56f34..d605ba5a4 100644 --- a/packages/core/server/src/locale/locale.ts +++ b/packages/core/server/src/locale/locale.ts @@ -14,10 +14,10 @@ export class Locale { constructor(app: Application) { this.app = app; this.app.on('afterLoad', async () => { - this.app.log.debug('load locale resource'); + this.app.log.debug('load locale resource', { submodule: 'locale', method: 'onAfterLoad' }); this.app.setMaintainingMessage('load locale resource'); await this.load(); - this.app.log.debug('locale resource loaded'); + this.app.log.debug('locale resource loaded', { submodule: 'locale', method: 'onAfterLoad' }); this.app.setMaintainingMessage('locale resource loaded'); }); } diff --git a/packages/core/server/src/plugin-manager/plugin-manager.ts b/packages/core/server/src/plugin-manager/plugin-manager.ts index da4cddbec..14f8bb683 100644 --- a/packages/core/server/src/plugin-manager/plugin-manager.ts +++ b/packages/core/server/src/plugin-manager/plugin-manager.ts @@ -231,7 +231,7 @@ export class PluginManager { console.error(error); // empty } - this.app.log.debug(`adding plugin [${options.name}]...`); + this.app.log.debug(`adding plugin...`, { method: 'add', submodule: 'plugin-manager', name: options.name }); let P: any; try { P = await PluginManager.resolvePlugin(options.packageName || plugin, isUpgrade, !!options.packageName); @@ -280,7 +280,7 @@ export class PluginManager { if (!plugin.enabled) { continue; } - this.app.logger.debug(`before load plugin [${name}]...`); + this.app.logger.debug(`before load plugin...`, { submodule: 'plugin-manager', method: 'load', name }); await plugin.beforeLoad(); } @@ -299,11 +299,11 @@ export class PluginManager { } await this.app.emitAsync('beforeLoadPlugin', plugin, options); - this.app.logger.debug(`loading plugin [${name}]...`); + this.app.logger.debug(`loading plugin...`, { submodule: 'plugin-manager', method: 'load', name }); await plugin.load(); plugin.state.loaded = true; await this.app.emitAsync('afterLoadPlugin', plugin, options); - this.app.logger.debug(`after load plugin [${name}]...`); + this.app.logger.debug(`after load plugin...`, { submodule: 'plugin-manager', method: 'load', name }); } this.app.setMaintainingMessage('loaded plugins'); @@ -527,11 +527,11 @@ export class PluginManager { await plugin.beforeLoad(); await this.app.emitAsync('beforeLoadPlugin', plugin, {}); - this.app.logger.debug(`loading plugin [${name}]...`); + this.app.logger.debug(`loading plugin...`, { submodule: 'plugin-manager', method: 'loadOne', name }); await plugin.load(); plugin.state.loaded = true; await this.app.emitAsync('afterLoadPlugin', plugin, {}); - this.app.logger.debug(`after load plugin [${name}]...`); + this.app.logger.debug(`after load plugin...`, { submodule: 'plugin-manager', method: 'loadOne', name }); this.app.setMaintainingMessage(`loaded plugin ${plugin.name}`); } diff --git a/packages/core/server/src/plugin.ts b/packages/core/server/src/plugin.ts index 5cfbf2ca1..55b316e2b 100644 --- a/packages/core/server/src/plugin.ts +++ b/packages/core/server/src/plugin.ts @@ -4,6 +4,7 @@ import { resolve } from 'path'; import { Application } from './application'; import { InstallOptions, getExposeChangelogUrl, getExposeReadmeUrl } from './plugin-manager'; import { checkAndGetCompatible } from './plugin-manager/utils'; +import { LoggerOptions, createLogger, getLoggerFilePath } from '@nocobase/logger'; export interface PluginInterface { beforeLoad?: () => void; @@ -38,7 +39,10 @@ export abstract class Plugin implements PluginInterface { } get log() { - return this.app.log; + return this.app.log.child({ + reqId: this.app.context.reqId, + module: this.name, + }); } get name() { @@ -77,6 +81,10 @@ export abstract class Plugin implements PluginInterface { return (this.options as any).name; } + createLogger(options: LoggerOptions) { + return this.app.createLogger(options); + } + afterAdd() {} beforeLoad() {} diff --git a/packages/core/test/src/server/mockServer.ts b/packages/core/test/src/server/mockServer.ts index dd5f677b7..1d0c9dfc0 100644 --- a/packages/core/test/src/server/mockServer.ts +++ b/packages/core/test/src/server/mockServer.ts @@ -94,7 +94,6 @@ export class MockServer extends Application { const databaseOptions = oldDatabase ? oldDatabase.options : options?.database || {}; const database = mockDatabase(databaseOptions); - database.setLogger(this._logger); database.setContext({ app: this }); return database; diff --git a/packages/plugins/@nocobase/plugin-acl/src/server/server.ts b/packages/plugins/@nocobase/plugin-acl/src/server/server.ts index 534228580..c7c67c254 100644 --- a/packages/plugins/@nocobase/plugin-acl/src/server/server.ts +++ b/packages/plugins/@nocobase/plugin-acl/src/server/server.ts @@ -361,7 +361,7 @@ export class PluginACL extends Plugin { const writeRolesToACL = async (app, options) => { const exists = await this.app.db.collectionExistsInDb('roles'); if (exists) { - this.log.info('write roles to ACL'); + this.log.info('write roles to ACL', { method: 'writeRolesToACL' }); await this.writeRolesToACL(); } }; diff --git a/packages/plugins/@nocobase/plugin-collection-manager/src/server/migrations/20221121111110-update-fk-type.ts b/packages/plugins/@nocobase/plugin-collection-manager/src/server/migrations/20221121111110-update-fk-type.ts index 3d8ee64d1..785db5a3d 100644 --- a/packages/plugins/@nocobase/plugin-collection-manager/src/server/migrations/20221121111110-update-fk-type.ts +++ b/packages/plugins/@nocobase/plugin-collection-manager/src/server/migrations/20221121111110-update-fk-type.ts @@ -66,7 +66,7 @@ export default class UpdateIdToBigIntMigrator extends Migration { throw err; } - this.app.log.info(`updated ${tableName}.${fieldName} to BIGINT`, tableName, fieldName); + this.app.log.info(`updated ${tableName}.${fieldName} to BIGINT`, { tableName, fieldName }); } }; diff --git a/packages/plugins/@nocobase/plugin-collection-manager/src/server/migrations/20221121111113-update-id-to-bigint.ts b/packages/plugins/@nocobase/plugin-collection-manager/src/server/migrations/20221121111113-update-id-to-bigint.ts index eebd2258a..cc70d75aa 100644 --- a/packages/plugins/@nocobase/plugin-collection-manager/src/server/migrations/20221121111113-update-id-to-bigint.ts +++ b/packages/plugins/@nocobase/plugin-collection-manager/src/server/migrations/20221121111113-update-id-to-bigint.ts @@ -100,7 +100,7 @@ export default class UpdateIdToBigIntMigrator extends Migration { } } - this.app.log.info(`updated ${tableName}.${fieldName} to BIGINT`, tableName, fieldName); + this.app.log.info(`updated ${tableName}.${fieldName} to BIGINT`, { tableName, fieldName }); } }; diff --git a/packages/plugins/@nocobase/plugin-collection-manager/src/server/repositories/collection-repository.ts b/packages/plugins/@nocobase/plugin-collection-manager/src/server/repositories/collection-repository.ts index eea623a8e..e8b861e9e 100644 --- a/packages/plugins/@nocobase/plugin-collection-manager/src/server/repositories/collection-repository.ts +++ b/packages/plugins/@nocobase/plugin-collection-manager/src/server/repositories/collection-repository.ts @@ -89,8 +89,11 @@ export class CollectionRepository extends Repository { if (lodash.isArray(skipField) && skipField.length) { lazyCollectionFields.set(instanceName, skipField); } - - this.database.logger.debug(`load ${instanceName} collection`); + this.database.logger.debug(`load collection`, { + instanceName, + submodule: 'CollectionRepository', + method: 'load', + }); this.app.setMaintainingMessage(`load ${instanceName} collection`); await nameMap[instanceName].load({ skipField }); @@ -98,14 +101,22 @@ export class CollectionRepository extends Repository { // load view fields for (const viewCollectionName of viewCollections) { - this.database.logger.debug(`load ${viewCollectionName} collection fields`); + this.database.logger.debug(`load collection fields`, { + submodule: 'CollectionRepository', + method: 'load', + viewCollectionName, + }); this.app.setMaintainingMessage(`load ${viewCollectionName} collection fields`); await nameMap[viewCollectionName].loadFields({}); } // load lazy collection field for (const [collectionName, skipField] of lazyCollectionFields) { - this.database.logger.debug(`load ${collectionName} collection fields`); + this.database.logger.debug(`load collection fields`, { + submodule: 'CollectionRepository', + method: 'load', + collectionName, + }); this.app.setMaintainingMessage(`load ${collectionName} collection fields`); await nameMap[collectionName].loadFields({ includeFields: skipField }); } diff --git a/packages/plugins/@nocobase/plugin-collection-manager/src/server/resourcers/sql.ts b/packages/plugins/@nocobase/plugin-collection-manager/src/server/resourcers/sql.ts index e838079a5..8126bf63b 100644 --- a/packages/plugins/@nocobase/plugin-collection-manager/src/server/resourcers/sql.ts +++ b/packages/plugins/@nocobase/plugin-collection-manager/src/server/resourcers/sql.ts @@ -55,7 +55,7 @@ export default { try { fields = model.inferFields(); } catch (err) { - ctx.logger.warn('resource: sql-collection, action: execute, error: ', err); + ctx.logger.warn(`resource: sql-collection, action: execute, error: ${err}`); fields = {}; } const sources = Array.from(new Set(Object.values(fields).map((field) => field.collection))); diff --git a/packages/plugins/@nocobase/plugin-collection-manager/src/server/server.ts b/packages/plugins/@nocobase/plugin-collection-manager/src/server/server.ts index e9a3aa3a0..5930629ba 100644 --- a/packages/plugins/@nocobase/plugin-collection-manager/src/server/server.ts +++ b/packages/plugins/@nocobase/plugin-collection-manager/src/server/server.ts @@ -238,7 +238,7 @@ export class CollectionManagerPlugin extends Plugin { }); const loadCollections = async () => { - this.app.log.debug('loading custom collections'); + this.log.debug('loading custom collections', { method: 'loadCollections' }); this.app.setMaintainingMessage('loading custom collections'); await this.app.db.getRepository('collections').load({ filter: this.loadFilter, diff --git a/packages/plugins/@nocobase/plugin-custom-request/src/server/plugin.ts b/packages/plugins/@nocobase/plugin-custom-request/src/server/plugin.ts index 22a60362e..0bd07553c 100644 --- a/packages/plugins/@nocobase/plugin-custom-request/src/server/plugin.ts +++ b/packages/plugins/@nocobase/plugin-custom-request/src/server/plugin.ts @@ -1,4 +1,4 @@ -import { Logger, LoggerOptions, Transports, createLogger, getLoggerFilePath } from '@nocobase/logger'; +import { Logger, LoggerOptions } from '@nocobase/logger'; import { InstallOptions, Plugin } from '@nocobase/server'; import { resolve } from 'path'; import { listByCurrentRole } from './actions/listByCurrentRole'; @@ -14,14 +14,10 @@ export class CustomRequestPlugin extends Plugin { } getLogger(): Logger { - const logger = createLogger({ - transports: [ - 'console', - Transports.dailyRotateFile({ - dirname: getLoggerFilePath('custom-request'), - filename: this.app.name + '-%DATE%.log', - }), - ], + const logger = this.createLogger({ + dirname: 'custom-request', + filename: '%DATE%.log', + transports: [...(process.env.NODE_ENV === 'production' ? ['dailyRotateFile'] : ['console'])], } as LoggerOptions); return logger; diff --git a/packages/plugins/@nocobase/plugin-data-visualization/src/server/actions/query.ts b/packages/plugins/@nocobase/plugin-data-visualization/src/server/actions/query.ts index 90608a314..06d4cff1d 100644 --- a/packages/plugins/@nocobase/plugin-data-visualization/src/server/actions/query.ts +++ b/packages/plugins/@nocobase/plugin-data-visualization/src/server/actions/query.ts @@ -253,7 +253,7 @@ export const parseVariables = async (ctx: Context, next: Next) => { const getUser = () => { return async ({ fields }) => { const userFields = fields.filter((f) => f && ctx.db.getFieldByPath('users.' + f)); - ctx.logger?.info('filter-parse: ', { userFields }); + ctx.logger?.info('parse filter variables', { userFields, method: 'parseVariables' }); if (!ctx.state.currentUser) { return; } @@ -264,8 +264,9 @@ export const parseVariables = async (ctx: Context, next: Next) => { filterByTk: ctx.state.currentUser.id, fields: userFields, }); - ctx.logger?.info('filter-parse: ', { + ctx.logger?.info('parse filter variables', { $user: user?.toJSON(), + method: 'parseVariables', }); return user; }; @@ -329,7 +330,6 @@ export const query = async (ctx: Context, next: Next) => { postProcess, ])(ctx, next); } catch (err) { - ctx.app.logger.error('charts query: ', err); ctx.throw(500, err); } }; diff --git a/packages/plugins/@nocobase/plugin-error-handler/src/server/error-handler.ts b/packages/plugins/@nocobase/plugin-error-handler/src/server/error-handler.ts index bddc4bd06..98e325520 100644 --- a/packages/plugins/@nocobase/plugin-error-handler/src/server/error-handler.ts +++ b/packages/plugins/@nocobase/plugin-error-handler/src/server/error-handler.ts @@ -26,7 +26,7 @@ export class ErrorHandler { try { await next(); } catch (err) { - ctx.log.error(err); + ctx.log.error(err.message, { method: 'error-handler', err: err.stack }); for (const handler of self.handlers) { if (handler.guard(err)) { diff --git a/packages/plugins/@nocobase/plugin-export/src/client/ExportDesigner.tsx b/packages/plugins/@nocobase/plugin-export/src/client/ExportDesigner.tsx index fa59c9619..8f02fa317 100644 --- a/packages/plugins/@nocobase/plugin-export/src/client/ExportDesigner.tsx +++ b/packages/plugins/@nocobase/plugin-export/src/client/ExportDesigner.tsx @@ -57,8 +57,8 @@ export const ExportDesigner = () => { default: fieldSchema?.['x-component-props']?.danger ? 'danger' : fieldSchema?.['x-component-props']?.type === 'primary' - ? 'primary' - : 'default', + ? 'primary' + : 'default', enum: [ { value: 'default', label: '{{t("Default")}}' }, { value: 'primary', label: '{{t("Highlight")}}' }, diff --git a/packages/plugins/@nocobase/plugin-import/src/client/ImportDesigner.tsx b/packages/plugins/@nocobase/plugin-import/src/client/ImportDesigner.tsx index 436715ec8..32dc2fbec 100644 --- a/packages/plugins/@nocobase/plugin-import/src/client/ImportDesigner.tsx +++ b/packages/plugins/@nocobase/plugin-import/src/client/ImportDesigner.tsx @@ -57,8 +57,8 @@ export const ImportDesigner = () => { default: fieldSchema?.['x-component-props']?.danger ? 'danger' : fieldSchema?.['x-component-props']?.type === 'primary' - ? 'primary' - : 'default', + ? 'primary' + : 'default', enum: [ { value: 'default', label: '{{t("Default")}}' }, { value: 'primary', label: '{{t("Highlight")}}' }, diff --git a/packages/plugins/@nocobase/plugin-localization-management/src/server/actions/localization.ts b/packages/plugins/@nocobase/plugin-localization-management/src/server/actions/localization.ts index 3873d3917..0d92d67ba 100644 --- a/packages/plugins/@nocobase/plugin-localization-management/src/server/actions/localization.ts +++ b/packages/plugins/@nocobase/plugin-localization-management/src/server/actions/localization.ts @@ -132,7 +132,7 @@ export const getTextsFromMenu = async (db: Database, migrate = false) => { const sync = async (ctx: Context, next: Next) => { const startTime = Date.now(); - ctx.app.logger.info('Start sync localization resources'); + ctx.logger.info('Start sync localization resources'); const resourcesInstance = await getResourcesInstance(ctx); const locale = ctx.get('X-Locale') || 'en-US'; const { type = [] } = ctx.action.params.values || {}; @@ -192,7 +192,7 @@ const sync = async (ctx: Context, next: Next) => { }); await resourcesInstance.updateCacheTexts(newTexts); }); - ctx.app.logger.info(`Sync localization resources done, ${Date.now() - startTime}ms`); + ctx.logger.info(`Sync localization resources done, ${Date.now() - startTime}ms`); await next(); }; diff --git a/packages/plugins/@nocobase/plugin-logger/.npmignore b/packages/plugins/@nocobase/plugin-logger/.npmignore new file mode 100644 index 000000000..65f5e8779 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/.npmignore @@ -0,0 +1,2 @@ +/node_modules +/src diff --git a/packages/plugins/@nocobase/plugin-logger/LICENSE b/packages/plugins/@nocobase/plugin-logger/LICENSE new file mode 100644 index 000000000..0ad25db4b --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/packages/plugins/@nocobase/plugin-logger/README.md b/packages/plugins/@nocobase/plugin-logger/README.md new file mode 100644 index 000000000..f0953db11 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/README.md @@ -0,0 +1 @@ +# @nocobase/plugin-logger diff --git a/packages/plugins/@nocobase/plugin-logger/client.d.ts b/packages/plugins/@nocobase/plugin-logger/client.d.ts new file mode 100755 index 000000000..6c459cbac --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/client.d.ts @@ -0,0 +1,2 @@ +export * from './dist/client'; +export { default } from './dist/client'; diff --git a/packages/plugins/@nocobase/plugin-logger/client.js b/packages/plugins/@nocobase/plugin-logger/client.js new file mode 100755 index 000000000..b6e3be70e --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/client.js @@ -0,0 +1 @@ +module.exports = require('./dist/client/index.js'); diff --git a/packages/plugins/@nocobase/plugin-logger/package.json b/packages/plugins/@nocobase/plugin-logger/package.json new file mode 100644 index 000000000..56b9f584b --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/package.json @@ -0,0 +1,19 @@ +{ + "name": "@nocobase/plugin-logger", + "displayName": "Logger", + "displayName.zh-CN": "日志", + "description": "Package and download log files", + "description.zh-CN": "打包下载日志文件", + "version": "0.18.0-alpha.2", + "main": "dist/server/index.js", + "devDependencies": { + "tar-fs": "^3.0.4", + "@types/tar-fs": "^2.0.2" + }, + "peerDependencies": { + "@nocobase/client": "0.x", + "@nocobase/server": "0.x", + "@nocobase/test": "0.x", + "@nocobase/actions": "0.x" + } +} diff --git a/packages/plugins/@nocobase/plugin-logger/server.d.ts b/packages/plugins/@nocobase/plugin-logger/server.d.ts new file mode 100755 index 000000000..c41081ddc --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/server.d.ts @@ -0,0 +1,2 @@ +export * from './dist/server'; +export { default } from './dist/server'; diff --git a/packages/plugins/@nocobase/plugin-logger/server.js b/packages/plugins/@nocobase/plugin-logger/server.js new file mode 100755 index 000000000..972842039 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/server.js @@ -0,0 +1 @@ +module.exports = require('./dist/server/index.js'); diff --git a/packages/plugins/@nocobase/plugin-logger/src/client/LogsDownloader.tsx b/packages/plugins/@nocobase/plugin-logger/src/client/LogsDownloader.tsx new file mode 100644 index 000000000..f49cb00bd --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/src/client/LogsDownloader.tsx @@ -0,0 +1,216 @@ +import { useAPIClient, useRequest } from '@nocobase/client'; +import React, { useCallback, useMemo } from 'react'; +import { Tree, Card, Alert, Typography, Input, Button, theme, Empty } from 'antd'; +import type { DataNode } from 'antd/lib/tree'; +import { FolderOutlined, FileOutlined } from '@ant-design/icons'; +import { useLoggerTranslation } from './locale'; +import { useMemoizedFn } from 'ahooks'; +const { Paragraph, Text } = Typography; + +type Log = string | LogDir; +type LogDir = { + name: string; + files: Log[]; +}; + +const Tips = React.memo(() => { + const { t } = useLoggerTranslation(); + return ( + + + [app]/request_*.log - {t('API request and response logs')} + + + [app]/system_*.log -{' '} + {t('Application, database, plugins and other system logs, the error level logs will be sent to')}{' '} + [app]/system_error_*.log + + + [app]/sql_*.log -{' '} + {t('SQL execution logs, printed by Sequelize when the db logging is enabled')} + + + ); +}); + +export const LogsDownloader = React.memo((props) => { + const { token } = theme.useToken(); + const { t: lang } = useLoggerTranslation(); + const t = useMemoizedFn(lang); + const api = useAPIClient(); + const [expandedKeys, setExpandedKeys] = React.useState(['0']); + const [searchValue, setSearchValue] = React.useState(''); + const [autoExpandParent, setAutoExpandParent] = React.useState(true); + const [checkedKeys, setCheckedKeys] = React.useState([]); + const { data } = useRequest(() => + api + .resource('logger') + .list() + .then((res) => res.data?.data), + ); + const data2tree = useCallback( + (data: Log[], parent: string): DataNode[] => + data.map((log: Log, index: number) => { + const key = `${parent}-${index}`; + if (typeof log === 'string') { + return { + title: log, + key, + icon: , + }; + } + return { + title: log.name, + key, + icon: , + children: data2tree(log.files, key), + }; + }), + [], + ); + const defaultTree: DataNode[] = useMemo(() => { + const files = data || []; + + return [ + { + title: t('All'), + key: '0', + children: data2tree(files as Log[], '0'), + }, + ]; + }, [data, data2tree, t]); + const onExpand = (newExpandedKeys: React.Key[]) => { + setExpandedKeys(newExpandedKeys); + setAutoExpandParent(false); + }; + const onSearch = (e: React.ChangeEvent) => { + const { value } = e.target; + const search = (data: DataNode[]) => { + return data.reduce((acc: DataNode[], node: DataNode) => { + if ((node.title as string)?.includes(value)) { + acc.push(node); + } + if (node.children) { + return [...acc, ...search(node.children)]; + } + return acc; + }, []); + }; + const newExpandedKeys = search(defaultTree).map((node: DataNode) => node.key); + setExpandedKeys(newExpandedKeys); + setSearchValue(value); + setAutoExpandParent(true); + setCheckedKeys([]); + }; + const tree = React.useMemo(() => { + if (!searchValue) { + return defaultTree; + } + const match = (data: DataNode[]): DataNode[] => { + const matched = []; + for (const node of data) { + const nodeTitle = node.title as string; + const index = nodeTitle.indexOf(searchValue); + const beforeStr = nodeTitle.substring(0, index); + const afterStr = nodeTitle.substring(index + searchValue.length); + const title = + index > -1 ? ( + + {beforeStr} + {searchValue} + {afterStr} + + ) : ( + {nodeTitle} + ); + + if (index > -1) { + matched.push({ ...node, title }); + } else if (node.children) { + const children = match(node.children); + if (children.length) { + matched.push({ ...node, title, children }); + } + } + } + return matched; + }; + return match(defaultTree); + }, [searchValue, defaultTree, token.colorPrimary]); + + const Download = () => { + const getValues = (data: DataNode[], parent: string) => { + return data.reduce((acc: string[], node: DataNode) => { + let title = node.title as string; + title = node.key === '0' ? title : `${parent}/${title}`; + if (node.children) { + return [...acc, ...getValues(node.children, node.key === '0' ? '' : title)]; + } else if (checkedKeys.includes(node.key as string) && node.key !== '0') { + acc.push(title); + } + return acc; + }, []); + }; + const files = getValues(defaultTree, ''); + if (!files.length) { + return; + } + api + .request({ + url: 'logger:download', + method: 'post', + responseType: 'blob', + data: { + files, + }, + }) + .then((res) => { + const url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/gzip' })); + const link = document.createElement('a'); + link.setAttribute('href', url); + link.setAttribute('download', 'logs.tar.gz'); + link.click(); + link.remove(); + }) + .catch((err) => { + console.log(err); + }); + }; + + return ( + + } type="info" showIcon /> + +

+ {tree.length ? ( + setCheckedKeys(keys)} + treeData={tree} + /> + ) : ( + + )} +
+ + + ); +}); diff --git a/packages/plugins/@nocobase/plugin-logger/src/client/index.tsx b/packages/plugins/@nocobase/plugin-logger/src/client/index.tsx new file mode 100644 index 000000000..67881a11d --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/src/client/index.tsx @@ -0,0 +1,22 @@ +import { Plugin } from '@nocobase/client'; +import { lang } from './locale'; +import { LogsDownloader } from './LogsDownloader'; + +export class PluginLoggerClient extends Plugin { + async afterAdd() { + // await this.app.pm.add() + } + + async beforeLoad() {} + + // You can get and modify the app instance here + async load() { + this.app.pluginSettingsManager.add('logger', { + title: lang('Logger'), + icon: 'FileTextOutlined', + Component: LogsDownloader, + }); + } +} + +export default PluginLoggerClient; diff --git a/packages/plugins/@nocobase/plugin-logger/src/client/locale/index.ts b/packages/plugins/@nocobase/plugin-logger/src/client/locale/index.ts new file mode 100644 index 000000000..cf7e7243b --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/src/client/locale/index.ts @@ -0,0 +1,12 @@ +import { i18n } from '@nocobase/client'; +import { useTranslation } from 'react-i18next'; + +export const NAMESPACE = 'logger'; + +export function lang(key: string) { + return i18n.t(key, { ns: NAMESPACE }); +} + +export function useLoggerTranslation() { + return useTranslation(NAMESPACE); +} diff --git a/packages/plugins/@nocobase/plugin-logger/src/index.ts b/packages/plugins/@nocobase/plugin-logger/src/index.ts new file mode 100644 index 000000000..7e74612df --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/src/index.ts @@ -0,0 +1,2 @@ +export * from './server'; +export { default } from './server'; diff --git a/packages/plugins/@nocobase/plugin-logger/src/locale/en-US.ts b/packages/plugins/@nocobase/plugin-logger/src/locale/en-US.ts new file mode 100644 index 000000000..1808bd019 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/src/locale/en-US.ts @@ -0,0 +1,11 @@ +export default { + Logger: 'Logger', + Search: 'Search', + Download: 'Download', + 'Download logs': 'Download logs', + 'API request and response logs': 'API request and response logs', + 'Application, database, plugins and other system logs, the error level logs will be sent to': + 'Application, database, plugins and other system logs, the error level logs will be sent to', + 'SQL execution logs, printed by Sequelize when the db logging is enabled': + 'SQL execution logs, printed by Sequelize when the db logging is enabled', +}; diff --git a/packages/plugins/@nocobase/plugin-logger/src/locale/zh-CN.ts b/packages/plugins/@nocobase/plugin-logger/src/locale/zh-CN.ts new file mode 100644 index 000000000..6b155dfe5 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/src/locale/zh-CN.ts @@ -0,0 +1,11 @@ +export default { + Logger: '日志', + Search: '搜索', + Download: '下载', + 'Download logs': '下载日志', + 'API request and response logs': 'API 接口请求和响应日志', + 'Application, database, plugins and other system logs, the error level logs will be sent to': + '应用、数据库、插件和其他系统日志,错误级别日志将会打印到', + 'SQL execution logs, printed by Sequelize when the db logging is enabled': + 'SQL 执行日志, 数据库日志启用时,Sequelize 打印的 SQL 执行日志', +}; diff --git a/packages/plugins/@nocobase/plugin-logger/src/server/collections/.gitkeep b/packages/plugins/@nocobase/plugin-logger/src/server/collections/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/packages/plugins/@nocobase/plugin-logger/src/server/index.ts b/packages/plugins/@nocobase/plugin-logger/src/server/index.ts new file mode 100644 index 000000000..b68aea57f --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/src/server/index.ts @@ -0,0 +1 @@ +export { default } from './plugin'; diff --git a/packages/plugins/@nocobase/plugin-logger/src/server/plugin.ts b/packages/plugins/@nocobase/plugin-logger/src/server/plugin.ts new file mode 100644 index 000000000..a84918214 --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/src/server/plugin.ts @@ -0,0 +1,26 @@ +import { InstallOptions, Plugin } from '@nocobase/server'; +import logger from './resourcer/logger'; + +export class PluginLoggerServer extends Plugin { + afterAdd() {} + + beforeLoad() {} + + async load() { + this.app.resource(logger); + this.app.acl.registerSnippet({ + name: `pm.${this.name}.logger`, + actions: ['logger:*'], + }); + } + + async install(options?: InstallOptions) {} + + async afterEnable() {} + + async afterDisable() {} + + async remove() {} +} + +export default PluginLoggerServer; diff --git a/packages/plugins/@nocobase/plugin-logger/src/server/resourcer/logger.ts b/packages/plugins/@nocobase/plugin-logger/src/server/resourcer/logger.ts new file mode 100644 index 000000000..cf1eea23d --- /dev/null +++ b/packages/plugins/@nocobase/plugin-logger/src/server/resourcer/logger.ts @@ -0,0 +1,91 @@ +import { Context, Next } from '@nocobase/actions'; +import { getLoggerFilePath } from '@nocobase/logger'; +import { readdir } from 'fs/promises'; +import { join } from 'path'; +import stream from 'stream'; +import { pack } from 'tar-fs'; +import zlib from 'zlib'; + +const tarFiles = (files: string[]): Promise => { + return new Promise((resolve, reject) => { + const passthrough = new stream.PassThrough(); + const gz = zlib.createGzip(); + pack(getLoggerFilePath(), { + entries: files, + }) + .on('data', (chunk) => { + passthrough.write(chunk); + }) + .on('end', () => { + passthrough.end(); + }) + .on('error', (err) => reject(err)); + passthrough + .on('data', (chunk) => { + gz.write(chunk); + }) + .on('end', () => { + gz.end(); + resolve(gz); + }) + .on('error', (err) => reject(err)); + gz.on('error', (err) => reject(err)); + }); +}; + +export default { + name: 'logger', + actions: { + list: async (ctx: Context, next: Next) => { + const path = getLoggerFilePath(); + const readDir = async (path: string) => { + const fileTree = []; + try { + const files = await readdir(path, { withFileTypes: true }); + for (const file of files) { + if (file.isDirectory()) { + const subFiles = await readDir(join(path, file.name)); + if (!subFiles.length) { + continue; + } + fileTree.push({ + name: file.name, + files: subFiles, + }); + } else if (file.name.endsWith('.log')) { + fileTree.push(file.name); + } + } + return fileTree; + } catch (err) { + ctx.log.error('readDir error', { err, path }); + return []; + } + }; + const files = await readDir(path); + ctx.body = files; + await next(); + }, + download: async (ctx: Context, next: Next) => { + let { files = [] } = ctx.action.params.values || {}; + const invalid = files.some((file: string) => !file.endsWith('.log')); + if (invalid) { + ctx.throw(400, ctx.t('Invalid file type: ') + invalid); + } + files = files.map((file: string) => { + if (file.startsWith('/')) { + return file.slice(1); + } + return file; + }); + try { + ctx.attachment('logs.tar.gz'); + ctx.body = await tarFiles(files); + } catch (err) { + ctx.log.error(`download error: ${err.message}`, { files, err: err.stack }); + ctx.throw(500, ctx.t('Download logs failed.')); + } + await next(); + }, + }, +}; diff --git a/packages/plugins/@nocobase/plugin-oidc/src/server/oidc-auth.ts b/packages/plugins/@nocobase/plugin-oidc/src/server/oidc-auth.ts index c0c8e8967..d8743bf61 100644 --- a/packages/plugins/@nocobase/plugin-oidc/src/server/oidc-auth.ts +++ b/packages/plugins/@nocobase/plugin-oidc/src/server/oidc-auth.ts @@ -54,7 +54,7 @@ export class OIDCAuth extends BaseAuth { const token = ctx.cookies.get(cookieName); const search = new URLSearchParams(values.state); if (search.get('token') !== token) { - ctx.app.logger.warn('odic-auth: state mismatch'); + ctx.logger.error('nocobase_oidc state mismatch', { method: 'validate' }); return null; } const client = await this.createOIDCClient(); diff --git a/packages/plugins/@nocobase/plugin-theme-editor/src/client/components/ThemeCard.tsx b/packages/plugins/@nocobase/plugin-theme-editor/src/client/components/ThemeCard.tsx index 45607d1f5..d333a85c3 100644 --- a/packages/plugins/@nocobase/plugin-theme-editor/src/client/components/ThemeCard.tsx +++ b/packages/plugins/@nocobase/plugin-theme-editor/src/client/components/ThemeCard.tsx @@ -259,18 +259,18 @@ const ThemeCard = (props: Props) => { item.id === currentThemeId ? t('Current') : item.id === defaultThemeId - ? t('Default') - : item.optional - ? t('Optional') - : t('Non-optional'); + ? t('Default') + : item.optional + ? t('Optional') + : t('Non-optional'); const color = item.id === currentThemeId ? 'processing' : item.id === defaultThemeId - ? 'default' - : item.optional - ? 'success' - : 'error'; + ? 'default' + : item.optional + ? 'success' + : 'error'; return ( diff --git a/packages/plugins/@nocobase/plugin-workflow-manual/src/client/WorkflowTodo.tsx b/packages/plugins/@nocobase/plugin-workflow-manual/src/client/WorkflowTodo.tsx index 209a1573c..e2201d2e0 100644 --- a/packages/plugins/@nocobase/plugin-workflow-manual/src/client/WorkflowTodo.tsx +++ b/packages/plugins/@nocobase/plugin-workflow-manual/src/client/WorkflowTodo.tsx @@ -508,8 +508,8 @@ function useFormBlockProps() { ? 'readPretty' : 'disabled' : user?.data?.id !== userJob.userId - ? 'disabled' - : 'editable'; + ? 'disabled' + : 'editable'; useEffect(() => { form?.setPattern(pattern); diff --git a/packages/plugins/@nocobase/plugin-workflow/src/server/Plugin.ts b/packages/plugins/@nocobase/plugin-workflow/src/server/Plugin.ts index 41cea51cd..1e2d14dc7 100644 --- a/packages/plugins/@nocobase/plugin-workflow/src/server/Plugin.ts +++ b/packages/plugins/@nocobase/plugin-workflow/src/server/Plugin.ts @@ -51,14 +51,10 @@ export default class WorkflowPlugin extends Plugin { return this.loggerCache.get(key); } - const logger = createLogger({ - transports: [ - ...(process.env.NODE_ENV !== 'production' ? ['console'] : []), - new winston.transports.File({ - filename: getLoggerFilePath('workflows', date, `${workflowId}.log`), - level: getLoggerLevel(), - }), - ], + const logger = this.createLogger({ + dirname: path.join('workflows', date), + filename: `${workflowId}.log`, + transports: [...(process.env.NODE_ENV !== 'production' ? ['console'] : ['file'])], } as LoggerOptions); this.loggerCache.set(key, logger); diff --git a/packages/presets/nocobase/package.json b/packages/presets/nocobase/package.json index e453ad77d..55a9a6f1d 100644 --- a/packages/presets/nocobase/package.json +++ b/packages/presets/nocobase/package.json @@ -34,6 +34,7 @@ "@nocobase/plugin-import": "0.18.0-alpha.2", "@nocobase/plugin-kanban": "0.18.0-alpha.2", "@nocobase/plugin-localization-management": "0.18.0-alpha.2", + "@nocobase/plugin-logger": "0.18.0-alpha.2", "@nocobase/plugin-map": "0.18.0-alpha.2", "@nocobase/plugin-math-formula-field": "0.18.0-alpha.2", "@nocobase/plugin-mobile-client": "0.18.0-alpha.2", diff --git a/packages/presets/nocobase/src/server/index.ts b/packages/presets/nocobase/src/server/index.ts index e4f242747..1d50925d7 100644 --- a/packages/presets/nocobase/src/server/index.ts +++ b/packages/presets/nocobase/src/server/index.ts @@ -35,6 +35,7 @@ export class PresetNocoBase extends Plugin { 'data-visualization', 'auth', 'sms-auth', + 'logger', 'custom-request', 'calendar', 'action-bulk-update', diff --git a/yarn.lock b/yarn.lock index a95a9c0d3..b5621bea3 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6458,6 +6458,21 @@ dependencies: "@types/superagent" "*" +"@types/tar-fs@^2.0.2": + version "2.0.2" + resolved "https://registry.npmjs.org/@types/tar-fs/-/tar-fs-2.0.2.tgz#d10b844cc1fcfa87de990a7cec350ee3d168c48b" + integrity sha512-XuZRAvdo7FbDfgQCNkc8NOdSae5XtG+of2mTSgJ85G4OG0miN4E8BTGT+JBTLO87RQ7iCwsIDCqCsHnf2IaSXA== + dependencies: + "@types/node" "*" + "@types/tar-stream" "*" + +"@types/tar-stream@*": + version "2.2.3" + resolved "https://registry.npmjs.org/@types/tar-stream/-/tar-stream-2.2.3.tgz#f17780c6628b27ade3cd8ff3be7deebb4480f462" + integrity sha512-if3mugZfjVkXOMZdFjIHySxY13r6GXPpyOlsDmLffvyI7tLz9wXE8BFjNivXsvUeyJ1KNlOpfLnag+ISmxgxPw== + dependencies: + "@types/node" "*" + "@types/tar@^6.1.5": version "6.1.10" resolved "https://registry.npmmirror.com/@types/tar/-/tar-6.1.10.tgz#10b0e12129f4af5909af82a055837116ab06f860" @@ -8230,6 +8245,11 @@ axios@^0.26.1: dependencies: follow-redirects "^1.14.8" +b4a@^1.6.4: + version "1.6.4" + resolved "https://registry.npmjs.org/b4a/-/b4a-1.6.4.tgz#ef1c1422cae5ce6535ec191baeed7567443f36c9" + integrity sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw== + babel-jest@^29.4.3: version "29.7.0" resolved "https://registry.npmmirror.com/babel-jest/-/babel-jest-29.7.0.tgz#f4369919225b684c56085998ac63dbd05be020d5" @@ -9117,7 +9137,7 @@ chalk@^1.1.1: strip-ansi "^3.0.0" supports-color "^2.0.0" -chalk@^4.0.0, chalk@^4.1.0, chalk@^4.1.1, chalk@^4.1.2: +chalk@^4, chalk@^4.0.0, chalk@^4.1.0, chalk@^4.1.1, chalk@^4.1.2: version "4.1.2" resolved "https://registry.npmmirror.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01" integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA== @@ -12752,6 +12772,11 @@ fast-diff@^1.1.2: resolved "https://registry.npmmirror.com/fast-diff/-/fast-diff-1.3.0.tgz#ece407fa550a64d638536cd727e129c61616e0f0" integrity sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw== +fast-fifo@^1.1.0, fast-fifo@^1.2.0: + version "1.3.2" + resolved "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz#286e31de96eb96d38a97899815740ba2a4f3640c" + integrity sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ== + fast-glob@3.2.12: version "3.2.12" resolved "https://registry.npmmirror.com/fast-glob/-/fast-glob-3.2.12.tgz#7f39ec99c2e6ab030337142da9e0c18f37afae80" @@ -17962,6 +17987,11 @@ mixin-deep@^1.2.0: for-in "^1.0.2" is-extendable "^1.0.1" +mkdirp-classic@^0.5.2: + version "0.5.3" + resolved "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz#fa10c9115cc6d8865be221ba47ee9bed78601113" + integrity sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A== + mkdirp-infer-owner@^2.0.0: version "2.0.0" resolved "https://registry.npmmirror.com/mkdirp-infer-owner/-/mkdirp-infer-owner-2.0.0.tgz#55d3b368e7d89065c38f32fd38e638f0ab61d316" @@ -20686,6 +20716,11 @@ queue-microtask@^1.2.2: resolved "https://registry.npmmirror.com/queue-microtask/-/queue-microtask-1.2.3.tgz#4929228bbc724dfac43e0efb058caf7b6cfb6243" integrity sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A== +queue-tick@^1.0.1: + version "1.0.1" + resolved "https://registry.npmjs.org/queue-tick/-/queue-tick-1.0.1.tgz#f6f07ac82c1fd60f82e098b417a80e52f1f4c142" + integrity sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag== + queue@6.0.1: version "6.0.1" resolved "https://registry.npmmirror.com/queue/-/queue-6.0.1.tgz#abd5a5b0376912f070a25729e0b6a7d565683791" @@ -23324,6 +23359,14 @@ streamsearch@^1.1.0: resolved "https://registry.npmmirror.com/streamsearch/-/streamsearch-1.1.0.tgz#404dd1e2247ca94af554e841a8ef0eaa238da764" integrity sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg== +streamx@^2.15.0: + version "2.15.1" + resolved "https://registry.npmjs.org/streamx/-/streamx-2.15.1.tgz#396ad286d8bc3eeef8f5cea3f029e81237c024c6" + integrity sha512-fQMzy2O/Q47rgwErk/eGeLu/roaFWV0jVsogDmrszM9uIw8L5OA+t+V93MgYlufNptfjmYR1tOMWhei/Eh7TQA== + dependencies: + fast-fifo "^1.1.0" + queue-tick "^1.0.1" + strict-uri-encode@^2.0.0: version "2.0.0" resolved "https://registry.npmmirror.com/strict-uri-encode/-/strict-uri-encode-2.0.0.tgz#b9c7330c7042862f6b142dc274bbcc5866ce3546" @@ -23835,6 +23878,15 @@ tar-fs@^1.15.3: pump "^1.0.0" tar-stream "^1.1.2" +tar-fs@^3.0.4: + version "3.0.4" + resolved "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.4.tgz#a21dc60a2d5d9f55e0089ccd78124f1d3771dbbf" + integrity sha512-5AFQU8b9qLfZCX9zp2duONhPmZv0hGYiBPJsyUdqMjzq/mqVpy/rEUSeHk1+YitmxugaptgBh5oDGU3VsAJq4w== + dependencies: + mkdirp-classic "^0.5.2" + pump "^3.0.0" + tar-stream "^3.1.5" + tar-stream@^1.1.2, tar-stream@^1.5.2, tar-stream@^1.5.4: version "1.6.2" resolved "https://registry.npmmirror.com/tar-stream/-/tar-stream-1.6.2.tgz#8ea55dab37972253d9a9af90fdcd559ae435c555" @@ -23859,6 +23911,15 @@ tar-stream@^2.2.0: inherits "^2.0.3" readable-stream "^3.1.1" +tar-stream@^3.1.5: + version "3.1.6" + resolved "https://registry.npmjs.org/tar-stream/-/tar-stream-3.1.6.tgz#6520607b55a06f4a2e2e04db360ba7d338cc5bab" + integrity sha512-B/UyjYwPpMBv+PaFSWAmtYjwdrlEaZQEhMIBFNC5oEG8lpiW8XjcSdmEaClj28ArfKScKHs2nshz3k2le6crsg== + dependencies: + b4a "^1.6.4" + fast-fifo "^1.2.0" + streamx "^2.15.0" + tar@6.1.11: version "6.1.11" resolved "https://registry.npmmirror.com/tar/-/tar-6.1.11.tgz#6760a38f003afa1b2ffd0ffe9e9abbd0eab3d621" @@ -24249,9 +24310,9 @@ trim-newlines@^3.0.0: resolved "https://registry.npmmirror.com/trim-newlines/-/trim-newlines-3.0.1.tgz#260a5d962d8b752425b32f3a7db0dcacd176c144" integrity sha512-c1PTsA3tYrIsLGkJkzHF+w9F2EyxfXGo4UyJc4pFL++FMjnq0HJS69T3M7d//gKrFKwy429bouPescbjecU+Zw== -triple-beam@^1.3.0: +triple-beam@^1.3.0, triple-beam@^1.4.1: version "1.4.1" - resolved "https://registry.npmmirror.com/triple-beam/-/triple-beam-1.4.1.tgz#6fde70271dc6e5d73ca0c3b24e2d92afb7441984" + resolved "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz#6fde70271dc6e5d73ca0c3b24e2d92afb7441984" integrity sha512-aZbgViZrg1QNcG+LULa7nhZpJTZSLm/mXnHXnbAbjmN5aSa0y7V+wvv6+4WaBtpISJzThKy+PIPxc1Nq1EJ9mg== trough@^2.0.0: