From d1c25e0d47a7738d5f87bec3e839b898bf19493c Mon Sep 17 00:00:00 2001 From: Ben Allfree Date: Thu, 19 Oct 2023 15:47:44 -0700 Subject: [PATCH] hotfix: logger tailing errors --- .../services/InstanceLoggerService/index.ts | 40 +++++++++++++++---- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/packages/daemon/src/services/InstanceLoggerService/index.ts b/packages/daemon/src/services/InstanceLoggerService/index.ts index 0d8fcf0d..c9dfca2a 100644 --- a/packages/daemon/src/services/InstanceLoggerService/index.ts +++ b/packages/daemon/src/services/InstanceLoggerService/index.ts @@ -1,5 +1,5 @@ import { mkInstanceDataPath, PUBLIC_DEBUG } from '$constants' -import { LoggerService } from '@pockethost/common' +import { createCleanupManager, LoggerService } from '@pockethost/common' import * as fs from 'fs' import { Tail } from 'tail' import * as winston from 'winston' @@ -51,6 +51,10 @@ function createOrGetLogger(instanceId: string, target: string): winston.Logger { export function InstanceLogger(instanceId: string, target: string) { const logger = createOrGetLogger(instanceId, target) + const { error, warn } = LoggerService() + .create('InstanceLogger') + .breadcrumb(instanceId) + .breadcrumb(target) const api = { info: (msg: string) => { @@ -65,16 +69,36 @@ export function InstanceLogger(instanceId: string, target: string) { ): UnsubFunc => { const logFile = mkInstanceDataPath(instanceId, `logs`, `${target}.log`) - const tail = new Tail(logFile, { nLines: linesBack }) + const cm = createCleanupManager() + let tid: any + cm.add(() => clearTimeout(tid)) + const check = () => { + try { + const tail = new Tail(logFile, { nLines: linesBack }) - tail.on('line', (line) => { - const entry = JSON.parse(line) - data(entry) - }) + tail.on('line', (line) => { + try { + const entry = JSON.parse(line) + data(entry) + } catch (e) { + data({ + level: 'info', + message: line, + time: new Date().toISOString(), + }) + } + }) + + cm.add(() => tail.unwatch()) + } catch (e) { + warn(e) + tid = setTimeout(check, 1000) + } + } + check() - // Return an unsubscribe function to remove the listener when done return () => { - tail.unwatch() + cm.shutdown() } }, }