Feature: add logs for picgo-server

ISSUES CLOSED: #627
This commit is contained in:
PiEgg 2021-04-24 17:56:56 +08:00
parent a657c51bb5
commit 2d9e9c0a00
6 changed files with 86 additions and 45 deletions

View File

@ -13,6 +13,7 @@ import util from 'util'
import { IPicGo } from 'picgo/dist/src/types' import { IPicGo } from 'picgo/dist/src/types'
import { showNotification, calcDurationRange } from '~/main/utils/common' import { showNotification, calcDurationRange } from '~/main/utils/common'
import { TALKING_DATA_EVENT } from '~/universal/events/constants' import { TALKING_DATA_EVENT } from '~/universal/events/constants'
import logger from '@core/picgo/logger'
const waitForShow = (webcontent: WebContents) => { const waitForShow = (webcontent: WebContents) => {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
@ -107,7 +108,7 @@ class Uploader {
return this return this
} }
upload (img?: IUploadOption): Promise<ImgInfo[]|false> { async upload (img?: IUploadOption): Promise<ImgInfo[]|false> {
if (this.uploading) { if (this.uploading) {
showNotification({ showNotification({
title: '上传失败', title: '上传失败',
@ -115,47 +116,36 @@ class Uploader {
}) })
return Promise.resolve(false) return Promise.resolve(false)
} }
return new Promise((resolve) => { try {
try { const startTime = Date.now()
const startTime = Date.now() this.uploading = true
this.uploading = true const output = await picgo.upload(img)
picgo.upload(img) this.uploading = false
picgo.once('finished', ctx => { if (Array.isArray(output) && output.every((item: ImgInfo) => item.imgUrl)) {
this.uploading = false if (this.webContents) {
if (ctx.output.every((item: ImgInfo) => item.imgUrl)) { handleTalkingData(this.webContents, {
if (this.webContents) { fromClipboard: !img,
handleTalkingData(this.webContents, { type: db.get('picBed.current') || 'smms',
fromClipboard: !img, count: img ? img.length : 1,
type: db.get('picBed.current') || 'smms', duration: Date.now() - startTime
count: img ? img.length : 1, } as IAnalyticsData)
duration: Date.now() - startTime }
} as IAnalyticsData) return output
} } else {
resolve(ctx.output) return false
} else {
resolve(false)
}
picgo.removeAllListeners('failed')
})
picgo.once('failed', (e: Error) => {
this.uploading = false
setTimeout(() => {
showNotification({
title: '上传失败',
body: util.format(e.stack),
clickToCopy: true
})
}, 500)
picgo.removeAllListeners('finished')
resolve(false)
})
} catch (e) {
this.uploading = false
picgo.removeAllListeners('failed')
picgo.removeAllListeners('finished')
resolve([])
} }
}) } catch (e) {
this.uploading = false
logger.error(e)
setTimeout(() => {
showNotification({
title: '上传失败',
body: util.format(e.stack),
clickToCopy: true
})
}, 500)
return false
}
} }
} }

View File

@ -0,0 +1,33 @@
import { app } from 'electron'
import fse from 'fs-extra'
import path from 'path'
import dayjs from 'dayjs'
import util from 'util'
const STORE_PATH = app.getPath('userData')
const LOG_PATH = path.join(STORE_PATH, '/picgo.log')
// since the error may occur in picgo-core
// so we can't use the log from picgo
const loggerWriter = (error: Error) => {
let log = `${dayjs().format('YYYY-MM-DD HH:mm:ss')} [PicGo ERROR] startup error`
if (error?.stack) {
log += `\n------Error Stack Begin------\n${util.format(error.stack)}\n-------Error Stack End-------\n`
} else {
const msg = JSON.stringify(error)
log += `${msg}\n`
}
fse.appendFileSync(LOG_PATH, log)
}
const handleProcessError = (error: Error) => {
console.error(error)
loggerWriter(error)
}
process.on('uncaughtException', error => {
handleProcessError(error)
})
process.on('unhandledRejection', (error: any) => {
handleProcessError(error)
})

View File

@ -1,3 +1,4 @@
import './errorHandler'
import { import {
app, app,
globalShortcut, globalShortcut,
@ -152,13 +153,11 @@ class LifeCycle {
process.on('message', data => { process.on('message', data => {
if (data === 'graceful-exit') { if (data === 'graceful-exit') {
app.quit() app.quit()
server.shutdown()
} }
}) })
} else { } else {
process.on('SIGTERM', () => { process.on('SIGTERM', () => {
app.quit() app.quit()
server.shutdown()
}) })
} }
} }

View File

@ -39,6 +39,7 @@ class Server {
private handleRequest = (request: http.IncomingMessage, response: http.ServerResponse) => { private handleRequest = (request: http.IncomingMessage, response: http.ServerResponse) => {
if (request.method === 'POST') { if (request.method === 'POST') {
if (!routers.getHandler(request.url!)) { if (!routers.getHandler(request.url!)) {
logger.warn(`[PicGo Server] don't support [${request.url}] url`)
handleResponse({ handleResponse({
response, response,
statusCode: 404, statusCode: 404,
@ -57,6 +58,7 @@ class Server {
try { try {
postObj = (body === '') ? {} : JSON.parse(body) postObj = (body === '') ? {} : JSON.parse(body)
} catch (err) { } catch (err) {
logger.error(`[PicGo Server]`, err)
return handleResponse({ return handleResponse({
response, response,
body: { body: {
@ -65,6 +67,7 @@ class Server {
} }
}) })
} }
logger.info(`[PicGo Server] get the request`)
const handler = routers.getHandler(request.url!) const handler = routers.getHandler(request.url!)
handler!({ handler!({
...postObj, ...postObj,
@ -73,6 +76,7 @@ class Server {
}) })
} }
} else { } else {
logger.warn(`[PicGo Server] don't support [${request.method}] method`)
response.statusCode = 404 response.statusCode = 404
response.end() response.end()
} }

View File

@ -18,6 +18,7 @@ router.post('/upload', async ({
try { try {
if (list.length === 0) { if (list.length === 0) {
// upload with clipboard // upload with clipboard
logger.info('[PicGo Server] upload clipboard file')
const res = await uploadWithClipboardFiles() const res = await uploadWithClipboardFiles()
if (res.success) { if (res.success) {
handleResponse({ handleResponse({
@ -29,10 +30,15 @@ router.post('/upload', async ({
}) })
} else { } else {
handleResponse({ handleResponse({
response response,
body: {
success: false,
message: 'upload error'
}
}) })
} }
} else { } else {
logger.info('[PicGo Server] upload files in list')
// upload with files // upload with files
const pathList = list.map(item => { const pathList = list.map(item => {
return { return {
@ -50,7 +56,11 @@ router.post('/upload', async ({
}) })
} else { } else {
handleResponse({ handleResponse({
response response,
body: {
success: false,
message: 'upload error'
}
}) })
} }
} }

View File

@ -1,3 +1,5 @@
import logger from '@core/picgo/logger'
export const handleResponse = ({ export const handleResponse = ({
response, response,
statusCode = 200, statusCode = 200,
@ -13,6 +15,9 @@ export const handleResponse = ({
header?: IObj, header?: IObj,
body?: any body?: any
}) => { }) => {
if (body?.success === false) {
logger.warn('[PicGo Server] upload failed, see picgo.log for more detail ↑')
}
response.writeHead(statusCode, header) response.writeHead(statusCode, header)
response.write(JSON.stringify(body)) response.write(JSON.stringify(body))
response.end() response.end()