Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update tslog execa #190

Merged
merged 5 commits into from
Jun 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -89,17 +89,17 @@
"@tigerconnect/ffi-napi": "4.0.3-tc3",
"@tigerconnect/ref-napi": "4.0.0-tc8",
"axios": "^1.4.0",
"chalk": "4",
"crypto-js": "^4.1.1",
"electron-squirrel-startup": "^1.0.0",
"electron-store": "^8.1.0",
"execa": "^5.1.1",
"execa": "^7.1.1",
"iconv-lite": "^0.6.3",
"ps-list": "^8.1.1",
"rotating-file-stream": "^3.1.0",
"semver": "^7.5.1",
"systeminformation": "^5.17.17",
"tar": "^6.1.15",
"tslog": "^3.3.4",
"unzipper": "^0.10.14"
}
}
2 changes: 2 additions & 0 deletions packages/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import DownloadManager from './downloadManager'
import { getAppBaseDir } from './utils/path'
import { setupHookProxy } from './utils/ipc-main'

require('source-map-support').install()

// Disable GPU Acceleration for Windows 7
if (release().startsWith('6.1')) app.disableHardwareAcceleration()

Expand Down
110 changes: 110 additions & 0 deletions packages/main/utils/log/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { format, formatWithOptions } from 'util'
import type { TLogLevel, TLogger, TLoggerController, TLoggerEnv } from './types'
import chalk from 'chalk'

let pathAlias = (p: string) => p

export type { TLogger, TLoggerEnv }

const LogLevel: TLogLevel = ['SILLY', 'DEBUG', 'TRACE', 'INFO', 'WARN', 'ERROR', 'FATAL']

export function initLogger(proj = process.cwd()) {
chalk.level = 3
pathAlias = p => {
return p.replace(proj, '')
}
}

export function createLogger(name: string, output: (env: TLoggerEnv) => void) {
const ctrl: TLoggerController = {
level: 0,
inspect: {},
}

function log(level: number, ...args: any[]) {
if (level < ctrl.level) {
return
}

const now = new Date()
const stack = new Error().stack?.split('\n')[3] ?? ''

const match = /^\s*at\s+([\s\S]+?)(?:\s+\(([\s\S]+?)\))?\s*$/.exec(stack)

const file = pathAlias(match?.[2] ?? match?.[1] ?? 'unknown')
const func = (match?.[2] ? match?.[1] : null) ?? '<anonymous>'

const env: TLoggerEnv = {
name,
source: {
file,
func,
stack,
},
date: {
year: now.getFullYear(),
month: now.getMonth() + 1,
date: now.getDate(),
hour: now.getHours(),
minute: now.getMinutes(),
second: now.getSeconds(),
msec: now.getMilliseconds(),
},
level: LogLevel[level],
content: {
pretty: formatWithOptions(
{
...ctrl.inspect,
colors: true,
},
'',
...args
).slice(1),
mono: formatWithOptions(
{
...ctrl.inspect,
colors: false,
},
'',
...args
).slice(1),
},
}
output(env)
}

const logger = {} as TLogger
for (const [l, s] of LogLevel.entries()) {
logger[s.toLowerCase() as Lowercase<typeof s>] = (...args) => {
log(l, ...args)
}
}
return [logger, ctrl] as const
}

export function createPresetFormatter(output: (out: { pretty: string; mono: string }) => void) {
return (env: TLoggerEnv) => {
const time = `${env.date.year.toString().padStart(4, '0')}-${env.date.month
.toString()
.padStart(2, '0')}-${env.date.date.toString().padStart(2, '0')} ${env.date.hour
.toString()
.padStart(2, '0')}-${env.date.minute.toString().padStart(2, '0')}:${env.date.second
.toString()
.padStart(2, '0')}.${env.date.msec.toString().padStart(3, '0')}`

output({
pretty: [
time,
chalk.bold(env.level),
`[${chalk.bold(env.name)} ${env.source.file} ${env.source.func}]`,
env.content.pretty,
].join('\t'),
mono: [
time,
env.level,
`[${env.name} ${env.source.file} ${env.source.func}]`,
env.content.mono,
].join('\t'),
})
}
}
46 changes: 46 additions & 0 deletions packages/main/utils/log/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import type { InspectOptions } from 'node:util'

type LowerAll<Ks extends string[]> = Ks extends [infer X, ...infer YS]
? X extends string
? YS extends string[]
? [Lowercase<X>, ...LowerAll<YS>]
: []
: []
: []

export type TLogLevel = ['SILLY', 'DEBUG', 'TRACE', 'INFO', 'WARN', 'ERROR', 'FATAL']
export type TLogLevelLo = LowerAll<TLogLevel>
export type TLogFunction = (...args: any[]) => void

export type TLogger = {
[key in TLogLevelLo[number]]: TLogFunction
}

export interface TLoggerEnv {
name: string
source: {
file: string
func: string
stack: string
}
date: {
year: number
month: number
date: number

hour: number
minute: number
second: number
msec: number // XXX
}
level: string
content: {
pretty: string
mono: string
}
}

export interface TLoggerController {
level: number // greater equal
inspect: InspectOptions
}
74 changes: 24 additions & 50 deletions packages/main/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,12 @@
import path from 'path'
import { format } from 'date-fns'
import tslog, { type ILogObject } from 'tslog'
import { createWriteStream, mkdirSync, existsSync, WriteStream } from 'fs'
import { createWriteStream, mkdirSync, existsSync, WriteStream, appendFileSync } from 'fs'
import { getAppBaseDir } from './path'
import { setupHookProxy } from './ipc-main'
import { createLogger, createPresetFormatter, initLogger, type TLogger } from './log'

class Logger {
public constructor() {
this.main_ = new tslog.Logger({
name: 'main',
})
this.renderer_ = new tslog.Logger({
name: 'renderer',
})

if (!existsSync(this.log_file_dir_)) {
mkdirSync(this.log_file_dir_)
}
Expand All @@ -23,72 +16,53 @@ class Logger {

this.log_file_ = createWriteStream(this.log_file_path_, { flags: 'a' })

this.main_.attachTransport(
{
silly: this.logToTransport,
debug: this.logToTransport,
trace: this.logToTransport,
info: this.logToTransport,
warn: this.logToTransport,
error: this.logToTransport,
fatal: this.logToTransport,
},
'debug'
)

this.renderer_.attachTransport(
{
silly: this.logToTransport,
debug: this.logToTransport,
trace: this.logToTransport,
info: this.logToTransport,
warn: this.logToTransport,
error: this.logToTransport,
fatal: this.logToTransport,
},
'debug'
)
const formatter = createPresetFormatter(out => {
console.log(out.pretty)
this.log_file_.write(out.mono + '\n')
})

initLogger()

const [ml, mc] = createLogger('main', formatter)
this.main_ = ml

const [rl, rc] = createLogger('renderer', formatter)
this.renderer_ = rl

// 提前初始化
setupHookProxy()
globalThis.main.Util = {
LogSilly: (...params) => {
params.pop()
this.renderer_.silly(...params)
},
LogDebug: (...params) => {
params.pop()
this.renderer_.debug(...params)
},
LogTrace: (...params) => {
params.pop()
this.renderer_.trace(...params)
},
LogInfo: (...params) => {
params.pop()
this.renderer_.info(...params)
},
LogWarn: (...params) => {
params.pop()
this.renderer_.warn(...params)
},
LogError: (...params) => {
params.pop()
this.renderer_.error(...params)
},
LogFatal: (...params) => {
params.pop()
this.renderer_.fatal(...params)
},
}
}

private readonly logToTransport = (logObject: ILogObject): void => {
this.main_
.getChildLogger({
colorizePrettyLogs: false,
dateTimeTimezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
prettyInspectOptions: {
colors: false,
depth: 20,
},
})
.printPrettyLog(this.log_file_, logObject)
}

public get logFilePath(): string {
return this.log_file_path_
}
Expand All @@ -97,14 +71,14 @@ class Logger {
return this.log_file_dir_
}

public get main(): tslog.Logger {
public get main() {
return this.main_
}

private readonly log_file_path_: string

private readonly main_: tslog.Logger
private readonly renderer_: tslog.Logger
private readonly main_: TLogger
private readonly renderer_: TLogger

private readonly log_file_: WriteStream

Expand Down
8 changes: 7 additions & 1 deletion packages/main/utils/shell.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import execa, { type ExecaError } from 'execa'
import { execa as EXECA, type ExecaError } from 'execa'
import iconv from 'iconv-lite'
import logger from '@main/utils/logger'
import { getPlatform } from '@main/utils/os'

let execa: typeof EXECA = () => void 0 as any

import('execa').then(({ execa: e }) => {
execa = e
})

interface ProcessOutput {
stdout: string
stderr: string
Expand Down
Loading