fix: lack of auto-cleaning mechanism for logs (#2003)
This commit is contained in:
parent
9e69946b73
commit
4e83cf3904
@ -26,6 +26,7 @@ import { cleanUpAndQuit } from './utils/clean'
|
||||
import { setupExtensions } from './utils/extension'
|
||||
import { setupCore } from './utils/setup'
|
||||
import { setupReactDevTool } from './utils/dev'
|
||||
import { cleanLogs } from './utils/log'
|
||||
|
||||
app
|
||||
.whenReady()
|
||||
@ -45,6 +46,7 @@ app
|
||||
}
|
||||
})
|
||||
})
|
||||
.then(() => cleanLogs())
|
||||
|
||||
app.once('window-all-closed', () => {
|
||||
cleanUpAndQuit()
|
||||
|
||||
67
electron/utils/log.ts
Normal file
67
electron/utils/log.ts
Normal file
@ -0,0 +1,67 @@
|
||||
import { getJanDataFolderPath } from '@janhq/core/node'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
|
||||
export function cleanLogs(
|
||||
maxFileSizeBytes?: number | undefined,
|
||||
daysToKeep?: number | undefined,
|
||||
delayMs?: number | undefined
|
||||
): void {
|
||||
const size = maxFileSizeBytes ?? 1 * 1024 * 1024 // 1 MB
|
||||
const days = daysToKeep ?? 7 // 7 days
|
||||
const delays = delayMs ?? 10000 // 10 seconds
|
||||
const logDirectory = path.join(getJanDataFolderPath(), 'logs')
|
||||
|
||||
// Perform log cleaning
|
||||
const currentDate = new Date()
|
||||
fs.readdir(logDirectory, (err, files) => {
|
||||
if (err) {
|
||||
console.error('Error reading log directory:', err)
|
||||
return
|
||||
}
|
||||
|
||||
files.forEach((file) => {
|
||||
const filePath = path.join(logDirectory, file)
|
||||
fs.stat(filePath, (err, stats) => {
|
||||
if (err) {
|
||||
console.error('Error getting file stats:', err)
|
||||
return
|
||||
}
|
||||
|
||||
// Check size
|
||||
if (stats.size > size) {
|
||||
fs.unlink(filePath, (err) => {
|
||||
if (err) {
|
||||
console.error('Error deleting log file:', err)
|
||||
return
|
||||
}
|
||||
console.log(
|
||||
`Deleted log file due to exceeding size limit: ${filePath}`
|
||||
)
|
||||
})
|
||||
} else {
|
||||
// Check age
|
||||
const creationDate = new Date(stats.ctime)
|
||||
const daysDifference = Math.floor(
|
||||
(currentDate.getTime() - creationDate.getTime()) /
|
||||
(1000 * 3600 * 24)
|
||||
)
|
||||
if (daysDifference > days) {
|
||||
fs.unlink(filePath, (err) => {
|
||||
if (err) {
|
||||
console.error('Error deleting log file:', err)
|
||||
return
|
||||
}
|
||||
console.log(`Deleted old log file: ${filePath}`)
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// Schedule the next execution with doubled delays
|
||||
setTimeout(() => {
|
||||
cleanLogs(maxFileSizeBytes, daysToKeep, delays * 2)
|
||||
}, delays)
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user