Skip to content

Commit

Permalink
feat: http-server 支持外部传入 logger, electron 实现 logger
Browse files Browse the repository at this point in the history
  • Loading branch information
WhiteMinds committed Dec 1, 2022
1 parent 8f9d078 commit 7d5f9a4
Show file tree
Hide file tree
Showing 10 changed files with 123 additions and 47 deletions.
3 changes: 2 additions & 1 deletion packages/electron/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@
"@autorecord/shared": "workspace:^",
"concurrently": "^7.4.0",
"env-paths": "^2.0.0",
"ffmpeg-static": "^5.0.2"
"ffmpeg-static": "^5.0.2",
"winston": "^3.8.2"
},
"devDependencies": {
"electron": "^20.1.1",
Expand Down
2 changes: 2 additions & 0 deletions packages/electron/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { logger } from './logger'
import { dirname, join } from 'path'
import { app, screen, shell, BrowserWindow, Menu, Tray } from 'electron'
import { startServer } from '@autorecord/http-server'
Expand Down Expand Up @@ -47,6 +48,7 @@ function initApp() {
startServer({
getSettings: async () => getSettings(),
setSettings: async (newSettings) => setSettings(newSettings),
logger,
// electron 在 asar 模式下对于一些文件相关的 api 有限制,而 fluent-ffmpeg 使用的 spawn
// 则在限制范围中,所以需要解包后的路径(解包是由 electron-builder 内部 hard code 实现的)。
// https://www.electronjs.org/fr/docs/latest/tutorial/asar-archives#executing-binaries-inside-asar-archive
Expand Down
44 changes: 44 additions & 0 deletions packages/electron/src/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import path from 'path'
import { createLogger, format, transports } from 'winston'
import { paths } from './env'

export const logger = createLogger({
level: 'debug',
format: format.combine(
format.label({ label: 'default' }),
format.timestamp(),
format.json()
),
transports: [
new transports.File({
filename: path.join(paths.log, 'client-error.log'),
level: 'error',
}),
new transports.File({
filename: path.join(paths.log, 'client-combined.log'),
}),
],
})

// winston 的 rejectionHandlers / exceptionHandlers 实现有 bug,配置后在遇到
// unhandledRejection 时会导致 logger 的 stream 永久 pause,所以这里手动写日志。
process.on('unhandledRejection', (error) => {
logger.error('unhandledRejection', error)
})
process.on('unhandleExceptions', (error) => {
logger.error('unhandleExceptions', error)
})

if (process.env.NODE_ENV !== 'production') {
logger.add(
new transports.Console({
format: format.combine(
format.colorize(),
format.align(),
format.printf(({ level, message, label, timestamp }) => {
return `${timestamp} [${label}] ${level}: ${message}`
})
),
})
)
}
21 changes: 16 additions & 5 deletions packages/http-server/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import './prepare'
import path from 'path'
import express from 'express'
import morgan from 'morgan'
Expand All @@ -11,18 +10,20 @@ import { Settings } from '@autorecord/shared'
import { paths } from './env'
import { PickPartial, readJSONFile, writeJSONFile } from './utils'
import { ServerOpts } from './types'
import { logger } from './logger'
import { createLogger } from './logger'

export * from './routes/api_types'

export async function startServer(
opts: PickPartial<ServerOpts, 'getSettings' | 'setSettings'> = {}
opts: PickPartial<ServerOpts, 'getSettings' | 'setSettings' | 'logger'> = {}
) {
const serverOpts: ServerOpts = {
...opts,
getSettings: opts.getSettings ?? defaultGetSettings,
setSettings: opts.setSettings ?? defaultSetSettings,
logger: opts.logger ?? console,
}
const { logger } = serverOpts

logger.info('initializing db')
await initDB()
Expand All @@ -31,7 +32,7 @@ export async function startServer(
if (opts.ffmpegPath != null) {
setFFMPEGPath(opts.ffmpegPath)
}
await initRecorderManager()
await initRecorderManager(serverOpts)

logger.info('HTTP server starting')
const app = express()
Expand Down Expand Up @@ -68,5 +69,15 @@ async function defaultSetSettings(newSettings: Settings) {

const isDirectlyRun = require.main === module
if (isDirectlyRun) {
void startServer()
const logger = createLogger()
// winston 的 rejectionHandlers / exceptionHandlers 实现有 bug,配置后在遇到
// unhandledRejection 时会导致 logger 的 stream 永久 pause,所以这里手动写日志。
process.on('unhandledRejection', (error) => {
logger.error('unhandledRejection', error)
})
process.on('unhandleExceptions', (error) => {
logger.error('unhandleExceptions', error)
})

void startServer({ logger })
}
79 changes: 43 additions & 36 deletions packages/http-server/src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,49 @@
import path from 'path'
import { createLogger, format, transports } from 'winston'
import {
createLogger as createWinstonLogger,
format,
transports,
} from 'winston'
import { paths } from './env'

export const logger = createLogger({
level: 'debug',
format: format.combine(
format.label({ label: 'default' }),
format.timestamp(),
format.json()
),
transports: [
new transports.File({
filename: path.join(paths.log, 'error.log'),
level: 'error',
}),
new transports.File({ filename: path.join(paths.log, 'combined.log') }),
],
})
export function createLogger() {
const logger = createWinstonLogger({
levels: {
error: 3,
warn: 4,
info: 6,
debug: 7,
},
level: 'debug',
format: format.combine(
format.label({ label: 'default' }),
format.timestamp(),
format.json()
),
transports: [
new transports.File({
filename: path.join(paths.log, 'server-error.log'),
level: 'error',
}),
new transports.File({
filename: path.join(paths.log, 'server-combined.log'),
}),
],
})

// winston 的 rejectionHandlers / exceptionHandlers 实现有 bug,配置后在遇到
// unhandledRejection 时会导致 logger 的 stream 永久 pause,所以这里手动写日志。
process.on('unhandledRejection', (error) => {
logger.error('unhandledRejection', error)
})
process.on('unhandleExceptions', (error) => {
logger.error('unhandleExceptions', error)
})
if (process.env.NODE_ENV !== 'production') {
logger.add(
new transports.Console({
format: format.combine(
format.colorize(),
format.align(),
format.printf(({ level, message, label, timestamp }) => {
return `${timestamp} [${label}] ${level}: ${message}`
})
),
})
)
}

if (process.env.NODE_ENV !== 'production') {
logger.add(
new transports.Console({
format: format.combine(
format.colorize(),
format.align(),
format.printf(({ level, message, label, timestamp }) => {
return `${timestamp} [${label}] ${level}: ${message}`
})
),
})
)
return logger
}
8 changes: 6 additions & 2 deletions packages/http-server/src/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { provider as providerForBilibili } from '@autorecord/bilibili-recorder'
import { isDebugMode, paths } from './env'
import { asyncDebounce, readJSONFile, writeJSONFile } from './utils'
import { insertRecord, updateRecordStopTime } from './db'
import { logger } from './logger'
import { ServerOpts } from './types'

const recordersConfigPath = path.join(paths.config, 'recorders.json')
const managerConfigPath = path.join(paths.config, 'manager.json')
Expand All @@ -18,7 +18,11 @@ export const recorderManager = createRecorderManager<RecorderExtra>({
providers: [providerForDouYu, providerForBilibili],
})

export async function initRecorderManager(): Promise<void> {
export async function initRecorderManager(
serverOpts: ServerOpts
): Promise<void> {
const { logger } = serverOpts

const managerConfig = await readJSONFile<ManagerConfig>(managerConfigPath, {
savePathRule: path.join(
paths.data,
Expand Down
2 changes: 0 additions & 2 deletions packages/http-server/src/prepare.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/http-server/src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import { router as managerRoutes } from './manager'
import { router as eventRoutes } from './event'
import { createRouter as createSettingRouter } from './setting'
import { ServerOpts } from '../types'
import { logger } from '../logger'
// import { respond } from './utils'

export function createRouter(serverOpts: ServerOpts) {
const { logger } = serverOpts
const router = Router()

router.use(recorderRoutes)
Expand Down
8 changes: 8 additions & 0 deletions packages/http-server/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import { Settings } from '@autorecord/shared'

export type LogFn = (data: unknown) => void

export interface ServerOpts {
getSettings: () => Promise<Settings>
setSettings: (newSettings: Settings) => Promise<Settings>
logger: {
error: LogFn
warn: LogFn
info: LogFn
debug: LogFn
}
ffmpegPath?: string
}
1 change: 1 addition & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ __metadata:
electron-vite: ^1.0.14
env-paths: ^2.0.0
ffmpeg-static: ^5.0.2
winston: ^3.8.2
languageName: unknown
linkType: soft

Expand Down

0 comments on commit 7d5f9a4

Please sign in to comment.