| const os = require('node:os')
|
| const { join, dirname, basename } = require('node:path')
|
| const fsMiniPass = require('fs-minipass')
|
| const fs = require('node:fs/promises')
|
| const { log } = require('proc-log')
|
| const { formatWithOptions } = require('./format')
|
|
|
| const padZero = (n, length) => n.toString().padStart(length.toString().length, '0')
|
|
|
| class LogFiles {
|
|
|
|
|
| #logStream = []
|
|
|
|
|
|
|
|
|
| #MAX_LOGS_PER_FILE = null
|
|
|
|
|
|
|
| #MAX_FILES_PER_PROCESS = null
|
|
|
| #fileLogCount = 0
|
| #totalLogCount = 0
|
| #path = null
|
| #logsMax = null
|
| #files = []
|
| #timing = false
|
|
|
| constructor ({
|
| maxLogsPerFile = 50_000,
|
| maxFilesPerProcess = 5,
|
| } = {}) {
|
| this.#MAX_LOGS_PER_FILE = maxLogsPerFile
|
| this.#MAX_FILES_PER_PROCESS = maxFilesPerProcess
|
| this.on()
|
| }
|
|
|
| on () {
|
| process.on('log', this.#logHandler)
|
| }
|
|
|
| off () {
|
| process.off('log', this.#logHandler)
|
| this.#endStream()
|
| }
|
|
|
| load ({ command, path, logsMax = Infinity, timing } = {}) {
|
| if (['completion'].includes(command)) {
|
| return
|
| }
|
|
|
|
|
| this.#path = path
|
| this.#logsMax = logsMax
|
| this.#timing = timing
|
|
|
|
|
| if (!this.#logStream) {
|
| return
|
| }
|
|
|
| log.verbose('logfile', `logs-max:${logsMax} dir:${this.#path}`)
|
|
|
|
|
|
|
| if (this.#logsMax > 0) {
|
| const initialFile = this.#openLogFile()
|
| if (initialFile) {
|
| for (const item of this.#logStream) {
|
| const formatted = this.#formatLogItem(...item)
|
| if (formatted !== null) {
|
| initialFile.write(formatted)
|
| }
|
| }
|
| this.#logStream = initialFile
|
| }
|
| }
|
|
|
| log.verbose('logfile', this.files[0] || 'no logfile created')
|
|
|
|
|
|
|
|
|
| return this.#cleanLogs()
|
| }
|
|
|
| get files () {
|
| return this.#files
|
| }
|
|
|
| get #isBuffered () {
|
| return Array.isArray(this.#logStream)
|
| }
|
|
|
| #endStream (output) {
|
| if (this.#logStream && !this.#isBuffered) {
|
| this.#logStream.end(output)
|
| this.#logStream = null
|
| }
|
| }
|
|
|
| #logHandler = (level, ...args) => {
|
|
|
| if (level === 'pause' || level === 'resume') {
|
| return
|
| }
|
|
|
|
|
| if (!this.#logStream) {
|
| return
|
| }
|
|
|
| if (this.#isBuffered) {
|
|
|
| this.#logStream.push([level, ...args])
|
| return
|
| }
|
|
|
| const logOutput = this.#formatLogItem(level, ...args)
|
| if (logOutput === null) {
|
| return
|
| }
|
|
|
|
|
| if (this.#fileLogCount >= this.#MAX_LOGS_PER_FILE) {
|
|
|
| this.#endStream(logOutput)
|
| if (this.#files.length >= this.#MAX_FILES_PER_PROCESS) {
|
|
|
| this.off()
|
| } else {
|
|
|
| this.#logStream = this.#openLogFile()
|
| }
|
| } else {
|
| this.#logStream.write(logOutput)
|
| }
|
| }
|
|
|
| #formatLogItem (level, title, ...args) {
|
|
|
| if (level === log.KEYS.timing && !this.#timing) {
|
| return null
|
| }
|
|
|
| this.#fileLogCount += 1
|
| const prefix = [this.#totalLogCount++, level, title || null]
|
| return formatWithOptions({ prefix, eol: os.EOL, colors: false }, ...args)
|
| }
|
|
|
| #getLogFilePath (count = '') {
|
| return `${this.#path}debug-${count}.log`
|
| }
|
|
|
| #openLogFile () {
|
|
|
| const count = this.#files.length
|
|
|
| try {
|
|
|
|
|
|
|
| const f = this.#getLogFilePath(padZero(count, this.#MAX_FILES_PER_PROCESS))
|
|
|
|
|
| const logStream = new fsMiniPass.WriteStreamSync(f, { flags: 'a' })
|
| if (count > 0) {
|
|
|
| this.#fileLogCount = 0
|
| }
|
| this.#files.push(logStream.path)
|
| return logStream
|
| } catch (e) {
|
|
|
| log.verbose('logfile', `could not be created: ${e}`)
|
| }
|
| }
|
|
|
| async #cleanLogs () {
|
|
|
|
|
|
|
|
|
| try {
|
| const logPath = this.#getLogFilePath()
|
| const patternFileName = basename(logPath)
|
|
|
| .replace(/\d/g, 'd')
|
|
|
| .replace('-.log', '')
|
|
|
| let files = await fs.readdir(
|
| dirname(logPath), {
|
| withFileTypes: true,
|
| encoding: 'utf-8',
|
| })
|
| files = files.sort((a, b) => basename(a.name).localeCompare(basename(b.name), 'en'))
|
|
|
| const logFiles = []
|
|
|
| for (const file of files) {
|
| if (!file.isFile()) {
|
| continue
|
| }
|
|
|
| const genericFileName = file.name.replace(/\d/g, 'd')
|
| const filePath = join(dirname(logPath), basename(file.name))
|
|
|
|
|
| if (
|
| genericFileName.includes(patternFileName)
|
| && genericFileName.endsWith('.log')
|
| && !this.#files.includes(filePath)
|
| ) {
|
| logFiles.push(filePath)
|
| }
|
| }
|
|
|
| const toDelete = logFiles.length - this.#logsMax
|
|
|
| if (toDelete <= 0) {
|
| return
|
| }
|
|
|
| log.silly('logfile', `start cleaning logs, removing ${toDelete} files`)
|
|
|
| for (const file of logFiles.slice(0, toDelete)) {
|
| try {
|
| await fs.rm(file, { force: true })
|
| } catch (e) {
|
| log.silly('logfile', 'error removing log file', file, e)
|
| }
|
| }
|
| } catch (e) {
|
|
|
| if (this.#logsMax > 0) {
|
| log.verbose('logfile', 'error cleaning log files', e)
|
| }
|
| } finally {
|
| log.silly('logfile', 'done cleaning log files')
|
| }
|
| }
|
| }
|
|
|
| module.exports = LogFiles
|
|
|