Skip to content

Commit daa7508

Browse files
committed
🐛 Fix: the issue of lost logs
1 parent 94a5f41 commit daa7508

File tree

6 files changed

+88
-72
lines changed

6 files changed

+88
-72
lines changed

src/core/PicGo.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ class PicGo extends EventEmitter {
4343
beforeUploadPlugins: new LifecyclePlugins('beforeUploadPlugins'),
4444
afterUploadPlugins: new LifecyclePlugins('afterUploadPlugins')
4545
}
46+
this.initConfigPath()
4647
this.log = new Logger(this)
4748
this.cmd = new Commander(this)
4849
this.pluginHandler = new PluginHandler(this)
@@ -54,29 +55,31 @@ class PicGo extends EventEmitter {
5455
LifecyclePlugins.currentPlugin = name
5556
}
5657

57-
initConfig (): void {
58+
private initConfigPath (): void {
5859
if (this.configPath === '') {
5960
this.configPath = homedir() + '/.picgo/config.json'
6061
}
6162
if (path.extname(this.configPath).toUpperCase() !== '.JSON') {
6263
this.configPath = ''
63-
this.log.error('The configuration file only supports JSON format.')
64-
return
64+
throw Error('The configuration file only supports JSON format.')
6565
}
6666
this.baseDir = path.dirname(this.configPath)
6767
const exist = fs.pathExistsSync(this.configPath)
6868
if (!exist) {
6969
fs.ensureFileSync(`${this.configPath}`)
7070
}
71+
}
72+
73+
private initConfig (): void {
7174
this.db = new DB(this)
7275
this.config = this.db.read().value()
7376
}
7477

75-
init (): any {
78+
private init (): void {
7679
try {
77-
// load self plugins
7880
this.Request = new Request(this)
7981
this.pluginLoader = new PluginLoader(this)
82+
// load self plugins
8083
this.setCurrentPluginName('picgo')
8184
uploaders(this)
8285
transformers(this)

src/lib/Logger.ts

Lines changed: 53 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -4,51 +4,67 @@ import dayjs from 'dayjs'
44
import fs from 'fs-extra'
55
import path from 'path'
66
import util from 'util'
7+
import { ILogType } from '../utils/enum'
8+
import {
9+
ILogArgvType,
10+
ILogArgvTypeWithError
11+
} from '../utils/interfaces'
712

813
class Logger {
9-
level: {
10-
[propName: string]: string
14+
private level = {
15+
[ILogType.success]: 'green',
16+
[ILogType.info]: 'blue',
17+
[ILogType.warn]: 'yellow',
18+
[ILogType.error]: 'red'
1119
}
12-
ctx: PicGo
20+
private ctx: PicGo
21+
// private logger: Console
22+
private logLevel: string
23+
private logPath: string
1324
constructor (ctx: PicGo) {
14-
this.level = {
15-
success: 'green',
16-
info: 'blue',
17-
warn: 'yellow',
18-
error: 'red'
19-
}
2025
this.ctx = ctx
2126
}
22-
protected handleLog (type: string, msg: string | Error): string | Error | undefined {
27+
private handleLog (type: ILogType, ...msg: ILogArgvTypeWithError[]): void {
2328
// if configPath is invalid then this.ctx.config === undefined
2429
// if not then check config.silent
2530
if (this.ctx.getConfig() === undefined || !this.ctx.getConfig('silent')) {
2631
let log = chalk[this.level[type]](`[PicGo ${type.toUpperCase()}]: `)
27-
log += msg
28-
console.log(log)
29-
process.nextTick(() => {
30-
this.handleWriteLog(type, msg, this.ctx)
31-
})
32-
return msg
32+
console.log(log, ...msg)
33+
this.logLevel = this.ctx.getConfig('settings.logLevel')
34+
const logPath = this.checkLogPathChange()
35+
setTimeout(() => {
36+
// The incoming logPath is a value
37+
// lock the path with a closure
38+
this.handleWriteLog(logPath, type, ...msg)
39+
}, 0)
3340
} else {
3441
return
3542
}
3643
}
3744

38-
protected handleWriteLog (type: string, msg: string | Error, ctx: PicGo): void {
45+
private checkLogPathChange (): string {
46+
const logPath = this.ctx.getConfig('settings.logPath') || path.join(this.ctx.baseDir, './picgo.log')
47+
if (logPath !== this.logPath) {
48+
this.logPath = logPath
49+
}
50+
return logPath
51+
}
52+
53+
protected handleWriteLog (logPath: string, type: string, ...msg: ILogArgvTypeWithError[]): void {
3954
try {
40-
const logLevel = this.ctx.getConfig('settings.logLevel')
41-
const logPath = this.ctx.getConfig('settings.logPath') || path.join(ctx.baseDir, './picgo.log')
42-
if (this.checkLogLevel(type, logLevel)) {
43-
const picgoLog = fs.createWriteStream(logPath, { flags: 'a', encoding: 'utf8' })
44-
let log = `${dayjs().format('YYYY-MM-DD HH:mm:ss')} [PicGo ${type.toUpperCase()}] ${msg}`
45-
let logger = new console.Console(picgoLog)
46-
if (typeof msg === 'object' && type === 'error') {
47-
log += `\n------Error Stack Begin------\n${util.format(msg.stack)}\n-------Error Stack End-------`
48-
}
49-
logger.log(log)
50-
picgoLog.destroy()
51-
logger = null
55+
if (this.checkLogLevel(type, this.logLevel)) {
56+
let log = `${dayjs().format('YYYY-MM-DD HH:mm:ss')} [PicGo ${type.toUpperCase()}] `
57+
msg.forEach((item: ILogArgvTypeWithError) => {
58+
if (typeof item === 'object' && type === 'error') {
59+
log += `\n------Error Stack Begin------\n${util.format(item.stack)}\n-------Error Stack End------- `
60+
} else {
61+
log += `${item} `
62+
}
63+
})
64+
log += '\n'
65+
fs.appendFile(logPath, log, (err: Error) => {
66+
if (err) console.log(err)
67+
})
5268
}
5369
} catch (e) {
5470
console.log(e)
@@ -66,20 +82,20 @@ class Logger {
6682
}
6783
}
6884

69-
success (msg: string | Error): string | Error | undefined {
70-
return this.handleLog('success', msg)
85+
success (...msg: ILogArgvType[]): void {
86+
return this.handleLog(ILogType.success, ...msg)
7187
}
7288

73-
info (msg: string | Error): string | Error | undefined {
74-
return this.handleLog('info', msg)
89+
info (...msg: ILogArgvType[]): void {
90+
return this.handleLog(ILogType.info, ...msg)
7591
}
7692

77-
error (msg: string | Error): string | Error | undefined {
78-
return this.handleLog('error', msg)
93+
error (...msg: ILogArgvTypeWithError[]): void {
94+
return this.handleLog(ILogType.error, ...msg)
7995
}
8096

81-
warn (msg: string | Error): string | Error | undefined {
82-
return this.handleLog('warn', msg)
97+
warn (...msg: ILogArgvType[]): void {
98+
return this.handleLog(ILogType.warn, ...msg)
8399
}
84100
}
85101

src/lib/PluginHandler.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ class PluginHandler {
6161
body: plugins
6262
})
6363
} else {
64-
const err = `插件更新失败,失败码为${result.code},错误日志为${result.data}`
64+
const err = `插件更新失败,失败码为${result.code},错误日志为 \n ${result.data}`
6565
this.ctx.log.error(err)
6666
this.ctx.emit('updateFailed', {
6767
title: '插件更新失败',
@@ -71,7 +71,7 @@ class PluginHandler {
7171
}
7272
execCommand (cmd: string, modules: string[], where: string, proxy: string = '', env: ProcessEnv = {}): Promise<Result> {
7373
const registry = this.ctx.getConfig('registry')
74-
return new Promise((resolve: any, reject: any): void => {
74+
return new Promise((resolve: any): void => {
7575
let args = [cmd].concat(modules).concat('--color=always').concat('--save')
7676
if (registry) {
7777
args = args.concat(`--registry=${registry}`)
@@ -95,7 +95,7 @@ class PluginHandler {
9595
if (!code) {
9696
resolve({ code: 0, data: output })
9797
} else {
98-
reject({ code: code, data: output })
98+
resolve({ code: code, data: output })
9999
}
100100
})
101101
// for users who haven't installed node.js

src/utils/enum.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export enum ILogType {
2+
success = 'success',
3+
info = 'info',
4+
warn = 'warn',
5+
error = 'error'
6+
}

src/utils/getClipboardImage.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,9 @@ const getClipboardImage = (ctx: PicGo): Promise<ClipboardImage> => {
4646
'-nologo',
4747
'-sta',
4848
'-executionpolicy', 'unrestricted',
49-
// fix windows 10 native cmd crash bug when "picgo upload"
50-
// https://github.com/PicGo/PicGo-Core/issues/32
51-
// '-windowstyle', 'hidden',
49+
// fix windows 10 native cmd crash bug when "picgo upload"
50+
// https://github.com/PicGo/PicGo-Core/issues/32
51+
// '-windowstyle','hidden',
5252
// '-noexit',
5353
'-file', scriptPath,
5454
imagePath

src/utils/interfaces.ts

Lines changed: 15 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import LifecyclePlugins from '../lib/LifecyclePlugins'
44
/**
55
* for plugin config
66
*/
7-
interface PluginConfig {
7+
export interface PluginConfig {
88
name: string
99
type: string
1010
required: boolean
@@ -15,7 +15,7 @@ interface PluginConfig {
1515
/**
1616
* for lifecycle plugins
1717
*/
18-
interface Helper {
18+
export interface Helper {
1919
transformer: LifecyclePlugins
2020
uploader: LifecyclePlugins
2121
beforeTransformPlugins: LifecyclePlugins
@@ -26,7 +26,7 @@ interface Helper {
2626
/**
2727
* for uploading image info
2828
*/
29-
interface ImgInfo {
29+
export interface ImgInfo {
3030
buffer?: Buffer
3131
base64Image?: string
3232
fileName?: string
@@ -36,45 +36,45 @@ interface ImgInfo {
3636
[propName: string]: any
3737
}
3838

39-
interface IPathTransformedImgInfo extends ImgInfo {
39+
export interface IPathTransformedImgInfo extends ImgInfo {
4040
success: boolean
4141
}
4242

4343
/**
4444
* for config options
4545
*/
46-
interface Config {
46+
export interface Config {
4747
[propName: string]: any
4848
}
4949

5050
/**
5151
* for plugin
5252
*/
53-
interface Plugin {
53+
export interface Plugin {
5454
handle (ctx: PicGo): void | Promise<any>
5555
[propName: string]: any
5656
}
5757

5858
/**
5959
* for spawn output
6060
*/
61-
interface Result {
61+
export interface Result {
6262
code: string | number
6363
data: string
6464
}
6565

6666
/**
6767
* for transformer - path
6868
*/
69-
interface ImgSize {
69+
export interface ImgSize {
7070
width: number
7171
height: number
7272
}
7373

7474
/**
7575
* for initUtils
7676
*/
77-
interface Options {
77+
export interface Options {
7878
template: string // template name
7979
dest: string // destination for template to generate
8080
hasSlash: boolean // check if is officail template
@@ -88,27 +88,18 @@ interface Options {
8888
/**
8989
* for clipboard image
9090
*/
91-
interface ClipboardImage {
91+
export interface ClipboardImage {
9292
imgPath: string
9393
isExistFile: boolean
9494
}
9595

9696
/**
9797
* for install command environment variable
9898
*/
99-
interface ProcessEnv {
99+
export interface ProcessEnv {
100100
[propName: string]: string | undefined
101101
}
102-
export {
103-
PluginConfig,
104-
ImgInfo,
105-
Config,
106-
Helper,
107-
Plugin,
108-
Result,
109-
ImgSize,
110-
Options,
111-
ClipboardImage,
112-
ProcessEnv,
113-
IPathTransformedImgInfo
114-
}
102+
103+
export type ILogArgvType = string | number
104+
105+
export type ILogArgvTypeWithError = ILogArgvType | Error

0 commit comments

Comments
 (0)