budibase/packages/backend-core/src/logging/system.ts

82 lines
2.2 KiB
TypeScript
Raw Normal View History

2023-07-10 13:25:24 +02:00
import fs from "fs"
import path from "path"
import * as rfs from "rotating-file-stream"
import env from "../environment"
import { budibaseTempDir } from "../objectStore"
2023-07-11 13:09:51 +02:00
const logsFileName = `budibase.log`
2023-07-10 16:52:26 +02:00
const budibaseLogsHistoryFileName = "budibase-logs-history.txt"
const logsPath = path.join(budibaseTempDir(), "systemlogs")
function getFullPath(fileName: string) {
return path.join(logsPath, fileName)
}
2023-07-10 13:25:24 +02:00
2023-07-11 13:48:52 +02:00
export function getSingleFileMaxSizeInfo(totalMaxSize: string) {
const regex = /(\d+)([A-Za-z])/
const match = totalMaxSize?.match(regex)
if (!match) {
console.warn(`totalMaxSize does not have a valid value`, {
totalMaxSize,
})
return undefined
}
const size = +match[1]
const unit = match[2]
if (size === 1) {
switch (unit) {
case "B":
return { size: `${size}B`, totalHistoryFiles: 1 }
case "K":
return { size: `${(size * 1000) / 2}B`, totalHistoryFiles: 1 }
case "M":
return { size: `${(size * 1000) / 2}K`, totalHistoryFiles: 1 }
case "G":
return { size: `${(size * 1000) / 2}M`, totalHistoryFiles: 1 }
default:
return undefined
}
}
if (size % 2 === 0) {
return { size: `${size / 2}${unit}`, totalHistoryFiles: 1 }
}
return { size: `1${unit}`, totalHistoryFiles: size }
}
2023-07-10 13:25:24 +02:00
export function localFileDestination() {
2023-07-11 13:48:52 +02:00
const fileInfo = getSingleFileMaxSizeInfo(env.ROLLING_LOG_MAX_SIZE)
2023-07-10 13:25:24 +02:00
const outFile = rfs.createStream(logsFileName, {
2023-07-11 13:48:52 +02:00
// As we have a rolling size, we want to half the max size
size: fileInfo?.size,
2023-07-10 16:52:26 +02:00
path: logsPath,
2023-07-11 13:48:52 +02:00
maxFiles: fileInfo?.totalHistoryFiles || 1,
2023-07-10 16:52:26 +02:00
immutable: true,
2023-07-10 17:17:45 +02:00
history: budibaseLogsHistoryFileName,
2023-07-10 16:52:26 +02:00
initialRotation: false,
2023-07-10 13:25:24 +02:00
})
return outFile
}
export function getLogReadStream() {
2023-07-10 16:52:26 +02:00
const streams = []
const historyFile = getFullPath(budibaseLogsHistoryFileName)
if (fs.existsSync(historyFile)) {
const fileContent = fs.readFileSync(historyFile, "utf-8")
const historyFiles = fileContent.split("\n")
for (const historyFile of historyFiles.filter(x => x)) {
streams.push(fs.readFileSync(historyFile))
}
2023-07-10 13:25:24 +02:00
}
2023-07-10 16:52:26 +02:00
streams.push(fs.readFileSync(getFullPath(logsFileName)))
const combinedContent = Buffer.concat(streams)
2023-07-10 13:25:24 +02:00
return combinedContent
}